<commit_before>( function (W) {

	W.gallery = {};

	W.gallery.Gallery = function ($view, settings) {
		var self = this;

		this.settings = settings || new W.gallery.Settings();
		this.$view = $view || null;

		this.juggler = new W.gallery.Juggler(this, this.settings.startsPlaying);
		this.controller = new W.gallery.Controller(this);

		this.exhibition = null;

		this.EXHIBIT_DID_CHANGE = "exhibit changed";
		this.EXHIBIT_WILL_CHANGE = "exhibit will change";
		this.STATE_DID_CHANGE = "state did change";

		this.events = new W.event.Dispatcher();

		// to do
		// setView();
		// getView();
		// setSettings();
		// getSettings();

		this.addExhibition = function ( exhibition ) {

			if ( self.exhibition === exhibition ) return;

			self.exhibition = exhibition;

			self.controller.clearQueue();

			self.controller.next();

			if ( self.settings.startsPlaying) {

				self.juggler.start();

			}

			exhibition.events.dispatch(exhibition.EXHIBITION_ADDED_TO_GALLERY);

		};

		this.getStatus = function () {

			var status = {

				totalExhibits 		: self.exhibition.length,
				currentExhibitIndex : self.exhibition.currentExhibit,
				isPlaying			: self.juggler.isPlaying,
				loops				: self.settings.loops

			}

			return status;
		};

	};

	W.gallery.Juggler = function (gallery, startsPlaying) {
		var self = this;

		this.intervalID = undefined;
		this.gallery = gallery;

		this.isPlaying = false;

		this.currentExhibit = null;
		this._nextExhibit = null;

		this.events = new W.event.Dispatcher();

		this.JUGGLER_DID_FINISH = 'juggler did finish';

		this.transitionTo = function (toExhibit) {

			self.gallery.events.dispatch(self.gallery.EXHIBIT_WILL_CHANGE);
			toExhibit.events.dispatch( toExhibit.EXHIBIT_WILL_APPEAR );

            this._nextExhibit = toExhibit;
            this.gallery.$view.append(this._nextExhibit.view);

            this._nextExhibit.view.fadeOut(0);
            this._nextExhibit.view.fadeIn(this.gallery.settings.transition_time, W.bind(this, this._transitionDidFinish));

		};

		this._transitionDidFinish = function () {

			if (!!self.currentExhibit) {

				self.currentExhibit = self._nextExhibit;

				self.currentExhibit.events.dispatch(self.currentExhibit.EXHIBIT_DID_APPEAR);

				self._nextExhibit = undefined;

			}

			self.events.dispatch(self.JUGGLER_DID_FINISH);

			self.gallery.events.dispatch(self.gallery.EXHIBIT_DID_CHANGE);

		};

		this.start = function () {

			self.isPlaying = true;

			self.intervalID = setInterval( self.next, self.gallery.settings.display_time );

			self.gallery.events.dispatch(self.gallery.STATE_DID_CHANGE);

		};

		this.next = function () {

			var nextExhibit = self.gallery.exhibition.getNextExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

			}  else {

				self.stop();

			}
		}

		this.stop = function () {

			self.isPlaying = false;

			clearInterval( self.intervalID );

			self.gallery.events.dispatch(self.gallery.STATE_DID_CHANGE);

		};

	};

	W.gallery.Controller = function (gallery) {
		var self = this;

		this._queue = [];
		this._ready = true;
		this.gallery = gallery;

		this.play = function () {

			if (!!self.gallery.juggler.isPlaying) return;

			self.gallery.juggler.start();

			return this;

		};

		this.goto = function ( index ) {

			if ( !self._readyOrQueue( self.goto ) ) break;

			var nextExhibit = self.gallery.exhibition.getExhibit( index );

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.last = function () {

			if ( !self._readyOrQueue( self.last )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getLastExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.first = function () {

			if ( !self._readyOrQueue( self.first )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getFirstExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.next = function () {

			if ( !self._readyOrQueue( self.next )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getNextExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.previous = function () {

			if ( !self._readyOrQueue( self.previous )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getPreviousExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.stop = function () {

			if (!self.gallery.juggler.isPlaying) return;

			self.gallery.juggler.stop();

			return this;

		};

		this.clearQueue = function () {

			self._queue = [];

		};

		this._actionCompleted = function () {

			self.gallery.juggler.events.removeEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted )

			if ( self._queue.length === 0 ) {
				self._ready = true;
			} else {
				var nextFn = this._queue.shift();
				nextFn();
			}
		};

		this._readyOrQueue = function ( action ) {
			if ( !!this._ready ) {

				return true;

			} else {

				self._queue = action;

				return false;
			}
		};
	};

	W.gallery.Settings = function (args) {
		var self = this,
			args = args || {};

		this.display_time = args["display_time"] || 2000;
		this.loops = args['loops'] || false;
		this.transition_time = args['transition_time_in'] || 1000;
		this.startsPlaying = args['startsPlaying'] || true;

	};

	W.gallery.Exhibition = function () {
		var self = this;

		this._exhibits = [];
		this.currentExhibit = -1;
		this.length = 0;

		this.events = new W.event.Dispatcher();

		this.EXHIBITION_ADDED_TO_GALLERY = "exhibition added to gallery";

		this.addExhibit = function ( exhibit ) {

			self._exhibits.push(exhibit);
			self.length = self._exhibits.length;
		};

		this.getNextExhibit = function () {

			if ( self.currentExhibit + 1 >= self._exhibits.length )  return false;

			self.currentExhibit++;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getPreviousExhibit = function () {

			if ( self.currentExhibit === 0 ) return false;

			self.currentExhibit--;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getLastExhibit = function () {

			if ( self.currentExhibit === self._exhibits.length - 1) return false;

			self.currentExhibit = self._exhibits.length - 1;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getFirstExhibit = function () {

			if ( self.currentExhibit === 0) return false;

			self.currentExhibit = 0;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getExhibit = function ( index ) {

			if ( self.length == 0 || self.currentExhibit == index) return false;

			self.currentExhibit = index;

			return self._exhibits[ self.currentExhibit ];

		};
	};

	W.gallery.Exhibit = function ( view ) {

		var self = this;

		this.view = view || null;

		this.events = new W.event.Dispatcher();

		this.EXHIBIT_WILL_APPEAR = "exhibit will appear";
		this.EXHIBIT_DID_APPEAR = "exhibit did appear";

		this.applyDefaultCSS = function () {

			self.view.css({
                'position' : 'absolute',
                'top' : 0,
                'left' : 0
            });

		};

	};

	W.gallery.Status = function (args) {

		var self = this;

	};

})(W);<commit_msg>updated<commit_after>( function (W) {

	W.gallery = {};

	W.gallery.Gallery = function ($view, settings) {
		var self = this;

		this.settings = settings || new W.gallery.Settings();
		this.$view = $view || null;

		this.juggler = new W.gallery.Juggler(this, this.settings.startsPlaying);
		this.controller = new W.gallery.Controller(this);

		this.exhibition = null;

		this.EXHIBIT_DID_CHANGE = "exhibit changed";
		this.EXHIBIT_WILL_CHANGE = "exhibit will change";
		this.STATE_DID_CHANGE = "state did change";

		this.events = new W.event.Dispatcher();

		// to do
		// setView();
		// getView();
		// getSettings();

		this.addExhibition = function ( exhibition ) {

			if ( self.exhibition === exhibition ) return;

			self.exhibition = exhibition;

			self.controller.clearQueue();

			self.controller.next();

			if ( self.settings.startsPlaying) {

				self.juggler.start();

			}

			exhibition.events.dispatch(exhibition.EXHIBITION_ADDED_TO_GALLERY);

		};

		this.getStatus = function () {

			var status = {

				totalExhibits 		: self.exhibition.length,
				currentExhibitIndex : self.exhibition.currentExhibit,
				isPlaying			: self.juggler.isPlaying,
				loops				: self.settings.loops

			}

			return status;
		};

		this.setSettings = function ( newSettings ) {

            W.l(self.settings);

			 if (newSettings == undefined) return;

			 for (var i in newSettings) {
            	if(newSettings[i] != undefined && isNaN(newSettings[i]) == false) { // error check
                	self.settings[i] = newSettings[i];
                } else {
                	W.w("slideshow", "invalid setting for:", i);
                }
            };

            W.l(self.settings);
		};

	};

	W.gallery.Juggler = function ( gallery, startsPlaying ) {
		var self = this;

		this.intervalID = undefined;
		this.gallery = gallery;

		this.isPlaying = false;

		this.currentExhibit = null;
		this._nextExhibit = null;

		this.events = new W.event.Dispatcher();

		this.JUGGLER_DID_FINISH = 'juggler did finish';

		this.transitionTo = function (toExhibit) {

			self.gallery.events.dispatch(self.gallery.EXHIBIT_WILL_CHANGE);
			toExhibit.events.dispatch( toExhibit.EXHIBIT_WILL_APPEAR );

            this._nextExhibit = toExhibit;
            this.gallery.$view.append(this._nextExhibit.view);

            this._nextExhibit.view.fadeOut(0);
            this._nextExhibit.view.fadeIn(this.gallery.settings.transition_time, W.bind(this, this._transitionDidFinish));

		};

		this._transitionDidFinish = function () {

			if (!!self.currentExhibit) {

				self.currentExhibit = self._nextExhibit;

				self.currentExhibit.events.dispatch(self.currentExhibit.EXHIBIT_DID_APPEAR);

				self._nextExhibit = undefined;

			}

			self.events.dispatch(self.JUGGLER_DID_FINISH);

			self.gallery.events.dispatch(self.gallery.EXHIBIT_DID_CHANGE);

		};

		this.start = function () {

			self.isPlaying = true;

			self.intervalID = setInterval( self.next, self.gallery.settings.display_time + self.gallery.settings.transition_time );

			self.gallery.events.dispatch(self.gallery.STATE_DID_CHANGE);

		};

		this.next = function () {

			var nextExhibit = self.gallery.exhibition.getNextExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

			}  else {

				self.stop();

			}
		}

		this.stop = function () {

			self.isPlaying = false;

			clearInterval( self.intervalID );

			self.gallery.events.dispatch(self.gallery.STATE_DID_CHANGE);

		};

	};

	W.gallery.Controller = function (gallery) {
		var self = this;

		this._queue = [];
		this._ready = true;
		this.gallery = gallery;

		this.play = function () {

			if (!!self.gallery.juggler.isPlaying) return;

			self.gallery.juggler.start();

			return this;

		};

		this.goto = function ( index ) {

			if ( !self._readyOrQueue( self.goto ) ) break;

			var nextExhibit = self.gallery.exhibition.getExhibit( index );

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.last = function () {

			if ( !self._readyOrQueue( self.last )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getLastExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.first = function () {

			if ( !self._readyOrQueue( self.first )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getFirstExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.next = function () {

			if ( !self._readyOrQueue( self.next )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getNextExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.previous = function () {

			if ( !self._readyOrQueue( self.previous )) break;

			self.gallery.juggler.stop();

			var nextExhibit = self.gallery.exhibition.getPreviousExhibit();

			if ( nextExhibit ) {

				self.gallery.juggler.transitionTo( nextExhibit ); // class back

				self.gallery.juggler.events.addEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted  );

			} else {

				this._actionCompleted();

			}

			return this;

		};

		this.stop = function () {

			if (!self.gallery.juggler.isPlaying) return;

			self.gallery.juggler.stop();

			return this;

		};

		this.clearQueue = function () {

			self._queue = [];

		};

		this._actionCompleted = function () {

			self.gallery.juggler.events.removeEventlistener( self.gallery.juggler.JUGGLER_DID_FINISH, self._actionCompleted )

			if ( self._queue.length === 0 ) {
				self._ready = true;
			} else {
				var nextFn = this._queue.shift();
				nextFn();
			}
		};

		this._readyOrQueue = function ( action ) {
			if ( !!this._ready ) {

				return true;

			} else {

				self._queue = action;

				return false;
			}
		};
	};

	W.gallery.Settings = function (args) {
		var self = this,
			args = args || {};

		this.display_time = args["display_time"] || 2000;
		this.loops = args['loops'] || false;
		this.transition_time = args['transition_time_in'] || 1000;
		this.startsPlaying = args['startsPlaying'] || true;

	};

	W.gallery.Exhibition = function () {
		var self = this;

		this._exhibits = [];
		this.currentExhibit = -1;
		this.length = 0;

		this.events = new W.event.Dispatcher();

		this.EXHIBITION_ADDED_TO_GALLERY = "exhibition added to gallery";

		this.addExhibit = function ( exhibit ) {

			self._exhibits.push(exhibit);
			self.length = self._exhibits.length;
		};

		this.getNextExhibit = function () {

			if ( self.currentExhibit + 1 >= self._exhibits.length )  return false;

			self.currentExhibit++;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getPreviousExhibit = function () {

			if ( self.currentExhibit === 0 ) return false;

			self.currentExhibit--;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getLastExhibit = function () {

			if ( self.currentExhibit === self._exhibits.length - 1) return false;

			self.currentExhibit = self._exhibits.length - 1;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getFirstExhibit = function () {

			if ( self.currentExhibit === 0) return false;

			self.currentExhibit = 0;

			return self._exhibits[ self.currentExhibit ];

		};

		this.getExhibit = function ( index ) {

			if ( self.length == 0 || self.currentExhibit == index) return false;

			self.currentExhibit = index;

			return self._exhibits[ self.currentExhibit ];

		};
	};

	W.gallery.Exhibit = function ( view, shouldApplyDefaultCSS ) {

		var self = this;

		this.view = view || null;

		if ( !(view instanceof jQuery && this.view != null) ) {
			this.view = $(this.view);
		}

		this.events = new W.event.Dispatcher();

		this.EXHIBIT_WILL_APPEAR = "exhibit will appear";
		this.EXHIBIT_DID_APPEAR = "exhibit did appear";

		this.shouldApplyDefaultCSS = shouldApplyDefaultCSS || false;

		this.applyDefaultCSS = function () {

			self.view.css({
                'position' : 'absolute',
                'top' : 0,
                'left' : 0
            });

		};

		if (shouldApplyDefaultCSS) {
			W.l("will apply defaults");
			this.applyDefaultCSS();
		}

	};

	W.gallery.Status = function (args) {

		var self = this;

	};

})(W);<|endoftext|>


<commit_before>

    var integrationBus = JSON.stringify({
      type: "IntegrationBus",
      integrationNodes: {
        type: "integrationNodes",
        uri: "/integrationbus/integrationnodes",
        integrationNode: [
          {
            name: "TESTNODE_Administrator",
            host: "somehost.ibm.com",
            mqtt: 1883,
            type: "integrationNode",
            integrationServers: {
              uri: "/apiv1/executiongroups",
              type: "executionGroups",
              integrationServer: [
                {
                  type: "executionGroup",
                  uri: "/apiv1/executiongroups/default",
                  name: "default",
                  applications: {
                     uri: "/apiv1/executiongroups/default/applications",
                     type: "applications",
                     application: [{
                         type: "application",
                         uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way",
                         name: "Hosie_HTTP one-way",
                         isRunning: true,
                         runMode: "running",
                         startMode: "Maintained",
                         libraries: {
                             uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/libraries",
                             type: "libraries",
                             library: [],
                             internal: "false"
                         },
                         messageFlows: {
                             uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows",
                             type: "messageFlows",
                             messageFlow: [{
                                 type: "messageFlow",
                                 uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows/RecordDistributor",
                                 propertiesUri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows/RecordDistributor/properties",
                                 UUID: "8a6b42c6-305f-4129-b42b-d9ff127bb272",
                                 name: "RecordDistributor",
                                 isRunning: true,
                                 runMode: "running",
                                 startMode: "Maintained",
                                 flowDesignUri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows/RecordDistributor/flowdesign",
                                 flowStatsTopic: "$SYS/Broker/TESTNODE_Administrator/Statistics/JSON/SnapShot/default/applications/Hosie_HTTP one-way/messageFlows/RecordDistributor"
                             }]
                         }
                     }]
                  }
              }]
            }
          }]
      }
    });

function APIv1Stub(){
    console.log("stubbing");
    sinon.log=function(str){
        console.log(str);
    }
    var stub = sinon.fakeServer.create();
    stub.respondWith("GET", "/apiv1/integrationbus?depth=8",integrationBus);
    stub.autoRespond=true;

    return stub;
}

var Paho ={};
Paho.MQTT = (function(){
    function client(){
        console.log("constructor");
        function publish(){
            console.log("publish");
            var message = {
                    destinationName :"IBM/IntegrationBus/TESTNODE_Administrator/Statistics/JSON/SnapShot/default/applications/Hosie_HTTP one-way/messageFlows/RecordDistributor",
                    payloadString   : JSON.stringify(
                      {
                        WMQIStatisticsAccounting : {
                            RecordType:"SnapShot",
                            RecordCode:"Snapshot",
                            MessageFlow:{
                                TotalCPUTime:12345
                            }
                        }
                      })
                    };
            this.onMessageArrived(message);
        }

        function connect(options){
            console.log("connect");
            setTimeout(options.onSuccess,100);
            setInterval($.proxy(publish,this),5000);

        }
        this.connect = connect;

        function subscribe(topic){
            console.log("subscribe:" + topic);
        }
        this.subscribe = subscribe;
    }
    return {
        Client:client
    }
})(window);

<commit_msg>flow stats on flow fails<commit_after>

    var integrationBus = JSON.stringify({
      type: "IntegrationBus",
      integrationNodes: {
        type: "integrationNodes",
        uri: "/integrationbus/integrationnodes",
        integrationNode: [
          {
            name: "TESTNODE_Administrator",
            host: "somehost.ibm.com",
            mqtt: 1883,
            type: "integrationNode",
            integrationServers: {
              uri: "/apiv1/executiongroups",
              type: "executionGroups",
              integrationServer: [
                {
                  type: "executionGroup",
                  uri: "/apiv1/executiongroups/default",
                  name: "default",
                  applications: {
                     uri: "/apiv1/executiongroups/default/applications",
                     type: "applications",
                     application: [{
                         type: "application",
                         uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way",
                         name: "Hosie_HTTP one-way",
                         isRunning: true,
                         runMode: "running",
                         startMode: "Maintained",
                         libraries: {
                             uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/libraries",
                             type: "libraries",
                             library: [],
                             internal: "false"
                         },
                         messageFlows: {
                             uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows",
                             type: "messageFlows",
                             messageFlow: [{
                                 type: "messageFlow",
                                 uri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows/RecordDistributor",
                                 propertiesUri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows/RecordDistributor/properties",
                                 UUID: "8a6b42c6-305f-4129-b42b-d9ff127bb272",
                                 name: "RecordDistributor",
                                 isRunning: true,
                                 runMode: "running",
                                 startMode: "Maintained",
                                 flowDesignUri: "/apiv1/executiongroups/default/applications/Hosie_HTTP%20one-way/messageflows/RecordDistributor/flowdesign",
                                 flowStatsTopic: "IBM/IntegrationBus/TESTNODE_Administrator/Statistics/JSON/SnapShot/default/applications/Hosie_HTTP one-way/messageFlows/RecordDistributor"
                             }]
                         }
                     }]
                  }
              }]
            }
          }]
      }
    });

function APIv1Stub(){
    console.log("stubbing");
    sinon.log=function(str){
        console.log(str);
    }
    var stub = sinon.fakeServer.create();
    stub.respondWith("GET", "/apiv1/integrationbus?depth=8",integrationBus);
    stub.autoRespond=true;

    return stub;
}

var Paho ={};
Paho.MQTT = (function(){
    function client(){
        console.log("constructor");
        function publish(){
            console.log("publish");
            var message = {
                    destinationName :"IBM/IntegrationBus/TESTNODE_Administrator/Statistics/JSON/SnapShot/default/applications/Hosie_HTTP one-way/messageFlows/RecordDistributor",
                    payloadString   : JSON.stringify(
                      {
                        WMQIStatisticsAccounting : {
                            RecordType:"SnapShot",
                            RecordCode:"Snapshot",
                            MessageFlow:{
                                TotalCPUTime:12345
                            }
                        }
                      })
                    };
            this.onMessageArrived(message);
        }

        function connect(options){
            console.log("connect");
            setTimeout(options.onSuccess,100);
            setInterval($.proxy(publish,this),5000);

        }
        this.connect = connect;

        function subscribe(topic){
            console.log("subscribe:" + topic);
        }
        this.subscribe = subscribe;
    }
    return {
        Client:client
    }
})(window);

<|endoftext|>


<commit_before>// @flow
import React from 'react'
import {
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
  Platform,
  View,
} from 'react-native'

type PropsType = {
  highlight?: boolean,
  onPress?: () => any,
  children?: any,
  borderless?: boolean,
  style?: any,
}
export const Touchable = ({
  children,
  style,
  highlight = true,
  borderless = false,
  onPress = () => {},
  ...props
}: PropsType) => {
  // The child <View> is required; the Touchable needs a View as its direct child.
  const content = <View style={style}>{children}</View>

  switch (Platform.OS) {
    default:
    case 'ios': {
      const Component = highlight ? TouchableHighlight : TouchableOpacity
      const innerProps = highlight
        ? {underlayColor: '#d9d9d9'}
        : {activeOpacity: 0.65}
      return (
        <Component onPress={onPress} {...innerProps} {...props}>
          {content}
        </Component>
      )
    }
    case 'android': {
      const canBorderless = Platform.Version >= 21
      const background = borderless && canBorderless
        ? TouchableNativeFeedback.SelectableBackgroundBorderless()
        : TouchableNativeFeedback.SelectableBackground()
      return (
        <TouchableNativeFeedback
          onPress={onPress}
          background={background}
          {...props}
        >
          {content}
        </TouchableNativeFeedback>
      )
    }
  }
}
<commit_msg>added custom container style options to touchable<commit_after>// @flow
import React from 'react'
import {
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
  Platform,
  View,
} from 'react-native'

type PropsType = {
  highlight?: boolean,
  onPress?: () => any,
  children?: any,
  borderless?: boolean,
  style?: any,
  containerStyle?: any,
}
export const Touchable = ({
  children,
  style,
  highlight = true,
  borderless = false,
  onPress = () => {},
  containerStyle,
  ...props
}: PropsType) => {
  // The child <View> is required; the Touchable needs a View as its direct child.
  const content = <View style={style}>{children}</View>

  switch (Platform.OS) {
    default:
    case 'ios': {
      const Component = highlight ? TouchableHighlight : TouchableOpacity
      const innerProps = highlight
        ? {underlayColor: '#d9d9d9'}
        : {activeOpacity: 0.65}
      return (
        <Component
          onPress={onPress}
          {...innerProps}
          style={containerStyle}
          {...props}
        >
          {content}
        </Component>
      )
    }
    case 'android': {
      const canBorderless = Platform.Version >= 21
      const background = borderless && canBorderless
        ? TouchableNativeFeedback.SelectableBackgroundBorderless()
        : TouchableNativeFeedback.SelectableBackground()
      return (
        <TouchableNativeFeedback
          onPress={onPress}
          background={background}
          style={containerStyle}
          {...props}
        >
          {content}
        </TouchableNativeFeedback>
      )
    }
  }
}
<|endoftext|>


<commit_before>import * as Chatbot from '../src/chatbot/chatbot-service';
import dialog from '../src/coaching-chatbot/dialog';
import * as Messenger from '../src/facebook-messenger/messenger-service';
import * as Sessions from '../src/util/sessions-service';
import * as sinon from 'sinon';

export function generate(discussions, states) {
  const messengerSpy = sinon.spy(Messenger, "send");
  var clock = sinon.useFakeTimers(new Date().getTime());

  const sessions = new Sessions();
  const bot = new Chatbot(dialog, sessions);

  sessions.db.load(states);

  let lines = [];
  let promise = bot.receive('', '');

  let messageQueue = {};

  function addBotReply(output) {
    for (let botReply of output) {
      for (let message of botReply.message.replace('\n\n', '\n').split('\n')) {
        if (message.length > 0) {
          lines.push('| ' + message + ' | |');
        }
      }
      if (botReply.quickReplies.length > 0) {
        lines.push('| [' +
          botReply.quickReplies
            .map((quickReply) => quickReply.title)
            .join('] [') + '] | |');
      }
    }
  }

  for (let scenario in discussions) {
    const messages = discussions[scenario].messages;
    const sessionID = discussions[scenario].session;

    if (discussions[scenario].time) {
      promise = promise.then(() => {
        clock = sinon.useFakeTimers(new Date(discussions[scenario].time).getTime());
      });
    }

    if (discussions[scenario].hide) {
      for (let message of messages) {
        promise = promise.then(() => {
          return bot.receive(sessionID, message);
        });
      }
    } else {
      promise = promise.then(() => {
        lines.push('# ' + scenario);
        lines.push('| Kehitystön vertaisohjausrobotti | ' + discussions[scenario].player + ' |');
        lines.push('|-|-|');
      });

      promise = promise.then(() => {
        if (messageQueue[sessionID] != undefined) {
          addBotReply(messageQueue[sessionID]);
          messageQueue[sessionID] = undefined;
        }
      });

      for (let message of messages) {
        promise = promise.then(() => {
          lines.push('| | ' + message + ' |');
          return bot.receive(sessionID, message);
        }).then((output) => {
          addBotReply(output);
        });
      }
    }

    promise = promise.then(() => {
      if (messengerSpy.callCount > 0) {
        for (let call of messengerSpy.args) {
          if (!messageQueue[call[0]]) {
            messageQueue[call[0]] = [];
          }
          messageQueue[call[0]].push({
            message: call[1],
            quickReplies: call[2] || {}
          });
        }
        messengerSpy.reset();
        clock.reset();
      }
    });
  }

  return promise
    .then(() => messengerSpy.restore())
    .then(() => {
      let scenarios = [];
      for (let line of lines) {
        if (line[0] == '#') {
          scenarios.push({
            title: line,
            content: []
          });
        } else {
          scenarios[scenarios.length - 1].content.push(line);
        }
      }
      return scenarios;
    });
}
<commit_msg>Improve discussion generation code<commit_after>import * as Chatbot from '../src/chatbot/chatbot-service';
import dialog from '../src/coaching-chatbot/dialog';
import * as Messenger from '../src/facebook-messenger/messenger-service';
import * as Sessions from '../src/util/sessions-service';
import * as sinon from 'sinon';

export function generate(discussions, states) {
  const messengerSpy = sinon.spy(Messenger, "send");
  var clock = sinon.useFakeTimers(new Date().getTime());

  const sessions = new Sessions();
  const bot = new Chatbot(dialog, sessions);

  sessions.db.load(states);

  let scenarios = [];
  let promise = bot.receive('', '');

  let messageQueue = {};

  function newTitle(title) {
    scenarios.push({
      title: '# ' + title,
      content: []
    });
  }

  function newContent(line) {
    scenarios[scenarios.length - 1].content.push(line);
  }

  function addBotReply(output) {
    for (let botReply of output) {
      for (let message of botReply.message.replace('\n\n', '\n').split('\n')) {
        if (message.length > 0) {
          newContent('| ' + message + ' | |');
        }
      }
      if (botReply.quickReplies.length > 0) {
        newContent('| [' +
          botReply.quickReplies
            .map((quickReply) => quickReply.title)
            .join('] [') + '] | |');
      }
    }
  }

  for (let scenario in discussions) {
    const messages = discussions[scenario].messages;
    const sessionID = discussions[scenario].session;

    if (discussions[scenario].time) {
      promise = promise.then(() => {
        clock = sinon.useFakeTimers(new Date(discussions[scenario].time).getTime());
      });
    }

    if (discussions[scenario].hide) {
      for (let message of messages) {
        promise = promise.then(() => {
          return bot.receive(sessionID, message);
        });
      }
    } else {
      promise = promise.then(() => {
        newTitle(scenario);
        newContent('| Kehitystön vertaisohjausrobotti | ' + discussions[scenario].player + ' |');
        newContent('|-|-|');
      });

      promise = promise.then(() => {
        if (messageQueue[sessionID] != undefined) {
          addBotReply(messageQueue[sessionID]);
          messageQueue[sessionID] = undefined;
        }
      });

      for (let message of messages) {
        promise = promise.then(() => {
          newContent('| | ' + message + ' |');
          return bot.receive(sessionID, message);
        }).then((output) => {
          addBotReply(output);
        });
      }
    }

    promise = promise.then(() => {
      if (messengerSpy.callCount > 0) {
        for (let call of messengerSpy.args) {
          if (!messageQueue[call[0]]) {
            messageQueue[call[0]] = [];
          }
          messageQueue[call[0]].push({
            message: call[1],
            quickReplies: call[2] || {}
          });
        }
        messengerSpy.reset();
        clock.reset();
      }
    });
  }

  return promise
    .then(() => messengerSpy.restore())
    .then(() => scenarios);
}
<|endoftext|>


<commit_before>import {extend, isObject} from 'vega-util';

export default function(configs) {
  var output = defaults();
  (configs || []).forEach(function(config) {
    var key;
    if (config) for (key in config) {
      output[key] = isObject(output[key])
        ? extend(output[key], config[key])
        : output[key] = config[key];
    }
  });
  return output;
}

var defaultFont = 'sans-serif',
    defaultSymbolSize = 30,
    defaultStrokeWidth = 2,
    defaultColor = '#4c78a8',
    black = "#000",
    gray = '#888',
    lightGray = '#ddd';

/**
 * Standard configuration defaults for Vega specification parsing.
 * Users can provide their own (sub-)set of these default values
 * by passing in a config object to the top-level parse method.
 */
function defaults() {
  return {
    // default padding around visualization
    padding: 0,

    // default for automatic sizing; options: "none", "pad", "fit"
    // or provide an object (e.g., {"type": "pad", "resize": true})
    autosize: 'pad',

    // default view background color
    // covers the entire view component
    background: null,

    // default event handling configuration
    // preventDefault for view-sourced event types except 'wheel'
    events: {
      defaults: {allow: ['wheel']}
    },

    // defaults for top-level group marks
    // accepts mark properties (fill, stroke, etc)
    // covers the data rectangle within group width/height
    group: null,

    // defaults for basic mark types
    // each subset accepts mark properties (fill, stroke, etc)
    mark: null,
    arc: { fill: defaultColor },
    area: { fill: defaultColor },
    image: null,
    line: {
      stroke: defaultColor,
      strokeWidth: defaultStrokeWidth
    },
    path: { stroke: defaultColor },
    rect: { fill: defaultColor },
    rule: { stroke: black },
    shape: { stroke: defaultColor },
    symbol: {
      fill: defaultColor,
      size: 64
    },
    text: {
      fill: black,
      font: defaultFont,
      fontSize: 11
    },

    // style definitions
    style: {
      // axis & legend labels
      "guide-label": {
        fill: black,
        font: defaultFont,
        fontSize: 10
      },
      // axis & legend titles
      "guide-title": {
        fill: black,
        font: defaultFont,
        fontSize: 11,
        fontWeight: 'bold'
      },
      // headers, including chart title
      "group-title": {
        fill: black,
        font: defaultFont,
        fontSize: 13,
        fontWeight: 'bold'
      },
      // defaults for styled point marks
      point: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth,
        shape: 'circle'
      },
      circle: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth
      },
      square: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth,
        shape: 'square'
      }
    },

    // defaults for axes
    axis: {
      minExtent: 0,
      maxExtent: 200,
      bandPosition: 0.5,
      domain: true,
      domainWidth: 1,
      domainColor: black,
      grid: false,
      gridWidth: 1,
      gridColor: lightGray,
      gridDash: [],
      gridOpacity: 1,
      labels: true,
      labelAngle: 0,
      labelLimit: 180,
      labelPadding: 2,
      ticks: true,
      tickColor: black,
      tickOffset: 0,
      tickRound: true,
      tickSize: 5,
      tickWidth: 1,
      titleAlign: 'center',
      titlePadding: 2
    },

    // correction for centering bias
    axisBand: {
      tickOffset: -1
    },

    // defaults for legends
    legend: {
      orient: 'right',
      offset: 18,
      padding: 0,
      entryPadding: 5,
      titlePadding: 5,
      gradientWidth: 100,
      gradientHeight: 20,
      gradientStrokeColor: lightGray,
      gradientStrokeWidth: 0,
      gradientLabelBaseline: 'top',
      gradientLabelOffset: 2,
      labelAlign: 'left',
      labelBaseline: 'middle',
      labelOffset: 8,
      labelLimit: 160,
      symbolType: 'circle',
      symbolSize: 100,
      symbolFillColor: 'transparent',
      symbolStrokeColor: gray,
      symbolStrokeWidth: 1.5,
      titleAlign: 'left',
      titleBaseline: 'top',
      titleLimit: 180
    },

    // defaults for group title
    title: {
      orient: 'top',
      anchor: 'middle',
      offset: 2
    },

    // defaults for scale ranges
    range: {
      category: {
        scheme: 'tableau10'
      },
      ordinal: {
        scheme: 'blues',
        extent: [0.2, 1]
      },
      heatmap: {
        scheme: 'viridis'
      },
      ramp: {
        scheme: 'blues',
        extent: [0.2, 1]
      },
      diverging: {
        scheme: 'blueorange'
      },
      symbol: [
        'circle',
        'square',
        'triangle-up',
        'cross',
        'diamond',
        'triangle-right',
        'triangle-down',
        'triangle-left'
      ]
    }
  };
}
<commit_msg>Change default axis domain/tickColor to gray<commit_after>import {extend, isObject} from 'vega-util';

export default function(configs) {
  var output = defaults();
  (configs || []).forEach(function(config) {
    var key;
    if (config) for (key in config) {
      output[key] = isObject(output[key])
        ? extend(output[key], config[key])
        : output[key] = config[key];
    }
  });
  return output;
}

var defaultFont = 'sans-serif',
    defaultSymbolSize = 30,
    defaultStrokeWidth = 2,
    defaultColor = '#4c78a8',
    black = "#000",
    gray = '#888',
    lightGray = '#ddd';

/**
 * Standard configuration defaults for Vega specification parsing.
 * Users can provide their own (sub-)set of these default values
 * by passing in a config object to the top-level parse method.
 */
function defaults() {
  return {
    // default padding around visualization
    padding: 0,

    // default for automatic sizing; options: "none", "pad", "fit"
    // or provide an object (e.g., {"type": "pad", "resize": true})
    autosize: 'pad',

    // default view background color
    // covers the entire view component
    background: null,

    // default event handling configuration
    // preventDefault for view-sourced event types except 'wheel'
    events: {
      defaults: {allow: ['wheel']}
    },

    // defaults for top-level group marks
    // accepts mark properties (fill, stroke, etc)
    // covers the data rectangle within group width/height
    group: null,

    // defaults for basic mark types
    // each subset accepts mark properties (fill, stroke, etc)
    mark: null,
    arc: { fill: defaultColor },
    area: { fill: defaultColor },
    image: null,
    line: {
      stroke: defaultColor,
      strokeWidth: defaultStrokeWidth
    },
    path: { stroke: defaultColor },
    rect: { fill: defaultColor },
    rule: { stroke: black },
    shape: { stroke: defaultColor },
    symbol: {
      fill: defaultColor,
      size: 64
    },
    text: {
      fill: black,
      font: defaultFont,
      fontSize: 11
    },

    // style definitions
    style: {
      // axis & legend labels
      "guide-label": {
        fill: black,
        font: defaultFont,
        fontSize: 10
      },
      // axis & legend titles
      "guide-title": {
        fill: black,
        font: defaultFont,
        fontSize: 11,
        fontWeight: 'bold'
      },
      // headers, including chart title
      "group-title": {
        fill: black,
        font: defaultFont,
        fontSize: 13,
        fontWeight: 'bold'
      },
      // defaults for styled point marks
      point: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth,
        shape: 'circle'
      },
      circle: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth
      },
      square: {
        size: defaultSymbolSize,
        strokeWidth: defaultStrokeWidth,
        shape: 'square'
      }
    },

    // defaults for axes
    axis: {
      minExtent: 0,
      maxExtent: 200,
      bandPosition: 0.5,
      domain: true,
      domainWidth: 1,
      domainColor: gray,
      grid: false,
      gridWidth: 1,
      gridColor: lightGray,
      gridDash: [],
      gridOpacity: 1,
      labels: true,
      labelAngle: 0,
      labelLimit: 180,
      labelPadding: 2,
      ticks: true,
      tickColor: gray,
      tickOffset: 0,
      tickRound: true,
      tickSize: 5,
      tickWidth: 1,
      titleAlign: 'center',
      titlePadding: 2
    },

    // correction for centering bias
    axisBand: {
      tickOffset: -1
    },

    // defaults for legends
    legend: {
      orient: 'right',
      offset: 18,
      padding: 0,
      entryPadding: 5,
      titlePadding: 5,
      gradientWidth: 100,
      gradientHeight: 20,
      gradientStrokeColor: lightGray,
      gradientStrokeWidth: 0,
      gradientLabelBaseline: 'top',
      gradientLabelOffset: 2,
      labelAlign: 'left',
      labelBaseline: 'middle',
      labelOffset: 8,
      labelLimit: 160,
      symbolType: 'circle',
      symbolSize: 100,
      symbolFillColor: 'transparent',
      symbolStrokeColor: gray,
      symbolStrokeWidth: 1.5,
      titleAlign: 'left',
      titleBaseline: 'top',
      titleLimit: 180
    },

    // defaults for group title
    title: {
      orient: 'top',
      anchor: 'middle',
      offset: 2
    },

    // defaults for scale ranges
    range: {
      category: {
        scheme: 'tableau10'
      },
      ordinal: {
        scheme: 'blues',
        extent: [0.2, 1]
      },
      heatmap: {
        scheme: 'viridis'
      },
      ramp: {
        scheme: 'blues',
        extent: [0.2, 1]
      },
      diverging: {
        scheme: 'blueorange'
      },
      symbol: [
        'circle',
        'square',
        'triangle-up',
        'cross',
        'diamond',
        'triangle-right',
        'triangle-down',
        'triangle-left'
      ]
    }
  };
}
<|endoftext|>


<commit_before>/*
 * 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.
 */

'use strict';

const AdminConnection = require('composer-admin').AdminConnection;
const BrowserFS = require('browserfs/dist/node/index');
const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection;
const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition;
const path = require('path');

require('chai').should();

const bfs_fs = BrowserFS.BFSRequire('fs');
const NS = 'org.acme.shipping.perishable';
let grower_id = 'farmer@email.com';
let importer_id = 'supermarket@email.com';
let factory;

describe('Perishable Shipping Network', () => {

    let businessNetworkConnection;

    before(() => {
        BrowserFS.initialize(new BrowserFS.FileSystem.InMemory());
        const adminConnection = new AdminConnection({ fs: bfs_fs });
        return adminConnection.createProfile('defaultProfile', {
            type: 'embedded'
        })
        .then(() => {
            return adminConnection.connect('defaultProfile', 'admin', 'Xurw3yU9zI0l');
        })
        .then(() => {
            return BusinessNetworkDefinition.fromDirectory(path.resolve(__dirname, '..'));
        })
        .then((businessNetworkDefinition) => {
            return adminConnection.deploy(businessNetworkDefinition);
        })
        .then(() => {
            businessNetworkConnection = new BusinessNetworkConnection({ fs: bfs_fs });
            return businessNetworkConnection.connect('defaultProfile', 'perishable-network', 'admin', 'Xurw3yU9zI0l');
        })
        .then(() => {
            // submit the setup demo transaction
            // this will create some sample assets and participants
            factory = businessNetworkConnection.getBusinessNetwork().getFactory();
            const setupDemo = factory.newTransaction(NS, 'SetupDemo');
            return businessNetworkConnection.submitTransaction(setupDemo);
        });
    });

    describe('#shipment', () => {

        it('should receive base price for a shipment within temperature range', () => {
            // submit the temperature reading
            const tempReading = factory.newTransaction(NS, 'TemperatureReading');
            tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
            tempReading.centigrade = 4.5;
            return businessNetworkConnection.submitTransaction(tempReading)
                .then(() => {
                    // submit the shipment received
                    const received = factory.newTransaction(NS, 'ShipmentReceived');
                    received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                    return businessNetworkConnection.submitTransaction(received);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                })
                .then((growerRegistry) => {
                    // check the grower's balance
                    return growerRegistry.get(grower_id);
                })
                .then((newGrower) => {
                    // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                    newGrower.accountBalance.should.equal(2500);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                })
                .then((importerRegistry) => {
                    // check the importer's balance
                    return importerRegistry.get(importer_id);
                })
                .then((newImporter) => {
                    newImporter.accountBalance.should.equal(-2500);
                })
                .then(() => {
                    return businessNetworkConnection.getAssetRegistry(NS + '.Shipment');
                })
                .then((shipmentRegistry) => {
                    // check the state of the shipment
                    return shipmentRegistry.get('SHIP_001');
                })
                .then((shipment) => {
                    shipment.status.should.equal('ARRIVED');
                });
        });

        it('should receive nothing for a late shipment', () => {
            // submit the temperature reading
            const tempReading = factory.newTransaction(NS, 'TemperatureReading');
            tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
            tempReading.centigrade = 4.5;
            return businessNetworkConnection.submitTransaction(tempReading)
                .then(() => {
                    // submit the shipment received
                    const received = factory.newTransaction(NS, 'ShipmentReceived');
                    received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                    const late = new Date();
                    late.setDate(late.getDate() + 2);
                    received.timestamp = late;
                    return businessNetworkConnection.submitTransaction(received);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                })
                .then((growerRegistry) => {
                    // check the grower's balance
                    return growerRegistry.get(grower_id);
                })
                .then((newGrower) => {
                    // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                    newGrower.accountBalance.should.equal(2500);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                })
                .then((importerRegistry) => {
                    // check the importer's balance
                    return importerRegistry.get(importer_id);
                })
                .then((newImporter) => {
                    newImporter.accountBalance.should.equal(-2500);
                });
        });

        it('should apply penalty for min temperature violation', () => {
            // submit the temperature reading
            const tempReading = factory.newTransaction(NS, 'TemperatureReading');
            tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
            tempReading.centigrade = 1;
            return businessNetworkConnection.submitTransaction(tempReading)
                .then(() => {
                    // submit the shipment received
                    const received = factory.newTransaction(NS, 'ShipmentReceived');
                    received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                    return businessNetworkConnection.submitTransaction(received);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                })
                .then((growerRegistry) => {
                    // check the grower's balance
                    return growerRegistry.get(grower_id);
                })
                .then((newGrower) => {
                    // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                    newGrower.accountBalance.should.equal(4000);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                })
                .then((importerRegistry) => {
                    // check the importer's balance
                    return importerRegistry.get(importer_id);
                })
                .then((newImporter) => {
                    newImporter.accountBalance.should.equal(-4000);
                });
        });

        it('should apply penalty for max temperature violation', () => {
            // submit the temperature reading
            const tempReading = factory.newTransaction(NS, 'TemperatureReading');
            tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
            tempReading.centigrade = 11;
            return businessNetworkConnection.submitTransaction(tempReading)
                .then(() => {
                    // submit the shipment received
                    const received = factory.newTransaction(NS, 'ShipmentReceived');
                    received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                    return businessNetworkConnection.submitTransaction(received);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                })
                .then((growerRegistry) => {
                    // check the grower's balance
                    return growerRegistry.get(grower_id);
                })
                .then((newGrower) => {
                    // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                    newGrower.accountBalance.should.equal(5000);
                })
                .then(() => {
                    return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                })
                .then((importerRegistry) => {
                    // check the importer's balance
                    return importerRegistry.get(importer_id);
                })
                .then((newImporter) => {
                    newImporter.accountBalance.should.equal(-5000);
                });
        });
    });
});
<commit_msg>Replace with version that works<commit_after>/*
 * 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.
 */

'use strict';

const AdminConnection = require('composer-admin').AdminConnection;
const BrowserFS = require('browserfs/dist/node/index');
const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection;
const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition;
const path = require('path');

require('chai').should();

const bfs_fs = BrowserFS.BFSRequire('fs');
const NS = 'org.acme.shipping.perishable';
let grower_id = 'farmer@email.com';
let importer_id = 'supermarket@email.com';
let factory;

describe('Perishable Shipping Network', () => {

    let businessNetworkConnection;

    before(() => {
    });

    /**
     * Reset the state of the blockchain
     * @return {Promise} A promise that will be resolved when complete.
     */
    function resetDemo() {
        BrowserFS.initialize(new BrowserFS.FileSystem.InMemory());
        const adminConnection = new AdminConnection({ fs: bfs_fs });
        return adminConnection.createProfile('defaultProfile', {
            type: 'embedded'
        })
        .then(() => {
            return adminConnection.connect('defaultProfile', 'admin', 'Xurw3yU9zI0l');
        })
        .then(() => {
            return BusinessNetworkDefinition.fromDirectory(path.resolve(__dirname, '..'));
        })
        .then((businessNetworkDefinition) => {
            return adminConnection.deploy(businessNetworkDefinition);
        })
        .then(() => {
            businessNetworkConnection = new BusinessNetworkConnection({ fs: bfs_fs });
            return businessNetworkConnection.connect('defaultProfile', 'perishable-network', 'admin', 'Xurw3yU9zI0l');
        })
        .then(() => {
            // submit the setup demo transaction
            // this will create some sample assets and participants
            factory = businessNetworkConnection.getBusinessNetwork().getFactory();
            const setupDemo = factory.newTransaction(NS, 'SetupDemo');
            return businessNetworkConnection.submitTransaction(setupDemo);
        });
    }

    describe('#shipment', () => {

        it('should receive base price for a shipment within temperature range', () => {
            resetDemo()
            .then(() => {
                // submit the temperature reading
                const tempReading = factory.newTransaction(NS, 'TemperatureReading');
                tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                tempReading.centigrade = 4.5;
                return businessNetworkConnection.submitTransaction(tempReading)
                    .then(() => {
                        // submit the shipment received
                        const received = factory.newTransaction(NS, 'ShipmentReceived');
                        received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                        return businessNetworkConnection.submitTransaction(received);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                    })
                    .then((growerRegistry) => {
                        // check the grower's balance
                        return growerRegistry.get(grower_id);
                    })
                    .then((newGrower) => {
                        // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                        newGrower.accountBalance.should.equal(2500);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                    })
                    .then((importerRegistry) => {
                        // check the importer's balance
                        return importerRegistry.get(importer_id);
                    })
                    .then((newImporter) => {
                        newImporter.accountBalance.should.equal(-2500);
                    })
                    .then(() => {
                        return businessNetworkConnection.getAssetRegistry(NS + '.Shipment');
                    })
                    .then((shipmentRegistry) => {
                        // check the state of the shipment
                        return shipmentRegistry.get('SHIP_001');
                    })
                    .then((shipment) => {
                        shipment.status.should.equal('ARRIVED');
                    });
            });
        });

        it('should receive nothing for a late shipment', () => {
            resetDemo()
            .then(() => {
                // submit the temperature reading
                const tempReading = factory.newTransaction(NS, 'TemperatureReading');
                tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                tempReading.centigrade = 4.5;
                return businessNetworkConnection.submitTransaction(tempReading)
                    .then(() => {
                        // submit the shipment received
                        const received = factory.newTransaction(NS, 'ShipmentReceived');
                        received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                        const late = new Date();
                        late.setDate(late.getDate() + 2);
                        received.timestamp = late;
                        return businessNetworkConnection.submitTransaction(received);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                    })
                    .then((growerRegistry) => {
                        // check the grower's balance
                        return growerRegistry.get(grower_id);
                    })
                    .then((newGrower) => {
                        // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                        newGrower.accountBalance.should.equal(2500);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                    })
                    .then((importerRegistry) => {
                        // check the importer's balance
                        return importerRegistry.get(importer_id);
                    })
                    .then((newImporter) => {
                        newImporter.accountBalance.should.equal(-2500);
                    });
            });
        });

        it('should apply penalty for min temperature violation', () => {
            resetDemo()
            .then(() => {
                // submit the temperature reading
                const tempReading = factory.newTransaction(NS, 'TemperatureReading');
                tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                tempReading.centigrade = 1;
                return businessNetworkConnection.submitTransaction(tempReading)
                    .then(() => {
                        // submit the shipment received
                        const received = factory.newTransaction(NS, 'ShipmentReceived');
                        received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                        return businessNetworkConnection.submitTransaction(received);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                    })
                    .then((growerRegistry) => {
                        // check the grower's balance
                        return growerRegistry.get(grower_id);
                    })
                    .then((newGrower) => {
                        // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                        newGrower.accountBalance.should.equal(4000);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                    })
                    .then((importerRegistry) => {
                        // check the importer's balance
                        return importerRegistry.get(importer_id);
                    })
                    .then((newImporter) => {
                        newImporter.accountBalance.should.equal(-4000);
                    });
            });
        });

        it('should apply penalty for max temperature violation', () => {
            resetDemo()
            .then(() => {
                // submit the temperature reading
                const tempReading = factory.newTransaction(NS, 'TemperatureReading');
                tempReading.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                tempReading.centigrade = 11;
                return businessNetworkConnection.submitTransaction(tempReading)
                    .then(() => {
                        // submit the shipment received
                        const received = factory.newTransaction(NS, 'ShipmentReceived');
                        received.shipment = factory.newRelationship(NS, 'Shipment', 'SHIP_001');
                        return businessNetworkConnection.submitTransaction(received);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Grower');
                    })
                    .then((growerRegistry) => {
                        // check the grower's balance
                        return growerRegistry.get(grower_id);
                    })
                    .then((newGrower) => {
                        // console.log(JSON.stringify(businessNetworkConnection.getBusinessNetwork().getSerializer().toJSON(newGrower)));
                        newGrower.accountBalance.should.equal(5000);
                    })
                    .then(() => {
                        return businessNetworkConnection.getParticipantRegistry(NS + '.Importer');
                    })
                    .then((importerRegistry) => {
                        // check the importer's balance
                        return importerRegistry.get(importer_id);
                    })
                    .then((newImporter) => {
                        newImporter.accountBalance.should.equal(-5000);
                    });
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

require('./lib/test-env.js');

const expect = require('chai').expect;
const request = require('superagent');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const serverCtrl = require('./lib/server-ctrl');
const cleanDB = require('./lib/clean-db');
const mockUser = require('./lib/user-mock');
const mockHospital = require('./lib/hospital-mock');

mongoose.Promise = Promise;

const server = require('../server');
const url = `http://localhost:${process.env.PORT}`;

const exampleHospital = {
  name: 'Seattle Childrens',
};

describe('testing hospital-router', function(){

  before(done => serverCtrl.serverUp(server, done));
  after(done => serverCtrl.serverDown(server, done));
  afterEach(done => cleanDB(done));

  describe('testing POST /api/hospital', function(){

    describe('testing valid POST request', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 200', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          if(err) return done(err);
          expect(res.status).to.equal(200);
          expect(res.body.name).to.equal(exampleHospital.name);
          done();
        });
      });
    });

    describe('testing POST request with invalid body', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 400', (done) => {
        request.post(`${url}/api/hospital`)
        .send('{youshallnotpass')
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(400);
          done();
        });
      });
    });

    describe('testing POST request with no body', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 400', (done) => {
        request.post(`${url}/api/hospital`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(400);
          done();
        });
      });
    });

    describe('testing POST request with invalid token', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 401', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: 'Bearer badtoken'})
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    });
  });

  describe('testing DELETE /api/hospital', function(){

    describe('testing valid DELETE request', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 204', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          if(err) return done(err);
          expect(res.status).to.equal(204);
          done();
        });
      });
    });

    describe('testing DELETE request with invalid id', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 404', (done) => {
        request.delete(`${url}/api/hospital/123`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          expect(res.status).to.equal(404);
          done();
        });
      });
    });

    describe('testing DELETE request with no id', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 404', (done) => {
        request.delete(`${url}/api/hospital/`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          expect(res.status).to.equal(404);
          done();
        });
      });
    });

    describe('testing DELETE request with no auth', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 400', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .end((err, res)=> {
          expect(res.status).to.equal(400);
          expect(res.text).to.equal('BadRequestError');
          done();
        });
      });
    });

    describe('testing DELETE request with invalid auth', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 400', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .set({Authorization: `${this.tempToken}`})
        .end((err, res)=> {
          expect(res.status).to.equal(400);
          expect(res.text).to.equal('BadRequestError');
          done();
        });
      });
    });

  });
});
<commit_msg>added more changes to hospital router test<commit_after>'use strict';

require('./lib/test-env.js');

const expect = require('chai').expect;
const request = require('superagent');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const serverCtrl = require('./lib/server-ctrl');
const cleanDB = require('./lib/clean-db');
const mockUser = require('./lib/user-mock');
const mockHospital = require('./lib/hospital-mock');

mongoose.Promise = Promise;

const server = require('../server');
const url = `http://localhost:${process.env.PORT}`;

const exampleHospital = {
  name: 'Seattle Childrens',
};

describe('testing hospital-router', function(){

  before(done => serverCtrl.serverUp(server, done));
  after(done => serverCtrl.serverDown(server, done));
  afterEach(done => cleanDB(done));

  describe('testing POST /api/hospital', function(){

    describe('testing valid POST request', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 200', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          if(err) return done(err);
          expect(res.status).to.equal(200);
          expect(res.body.name).to.equal(exampleHospital.name);
          done();
        });
      });
    });

    describe('testing POST request with invalid body', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 400', (done) => {
        request.post(`${url}/api/hospital`)
        .send('{youshallnotpass')
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(400);
          expect(res.text).to.equal('BadRequestError');
          done();
        });
      });
    });

    describe('testing POST request with no body', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 400', (done) => {
        request.post(`${url}/api/hospital`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(400);
          expect(res.text).to.equal('BadRequestError');
          done();
        });
      });
    });

    describe('testing POST request with invalid token', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 401', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: 'Bearer badtoken'})
        .end((err, res) => {
          expect(res.status).to.equal(401);
          expect(res.text).to.equal('UnauthorizedError');
          done();
        });
      });
    });
  });

  describe('testing DELETE /api/hospital', function(){

    describe('testing valid DELETE request', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 204', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          if(err) return done(err);
          expect(res.status).to.equal(204);
          done();
        });
      });
    });

    describe('testing DELETE request with invalid id', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 404', (done) => {
        request.delete(`${url}/api/hospital/123`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          expect(res.status).to.equal(404);
          expect(res.text).to.equal('NotFoundError');
          done();
        });
      });
    });

    describe('testing DELETE request with no id', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 404', (done) => {
        request.delete(`${url}/api/hospital/`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          expect(res.status).to.equal(404);
          done();
        });
      });
    });

    describe('testing DELETE request with no auth', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 400', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .end((err, res)=> {
          expect(res.status).to.equal(400);
          expect(res.text).to.equal('BadRequestError');
          done();
        });
      });
    });

    describe('testing DELETE request with invalid auth', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 400', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .set({Authorization: `${this.tempToken}`})
        .end((err, res)=> {
          expect(res.status).to.equal(400);
          expect(res.text).to.equal('BadRequestError');
          done();
        });
      });
    });

  });
});
<|endoftext|>


<commit_before>// @flow

import * as React from 'react'

import {TabNavigator} from '../components/tabbed-view'
import {TabBarIcon} from '../components/tabbar-icon'

import {OtherModesView} from './other-modes'
import {ConnectedXyzBusView, ConnectedXyzBusList} from './xyz'

export {ConnectedXyzBusView} from './xyz/view'
export {OtherModesDetailView} from './other-modes'
export {BusMap} from './bus'

export default TabNavigator(
	{
		ExpressLineBusView: {
			screen: ({navigation}) => (
				<ConnectedXyzBusView navigation={navigation} routeName="Express Bus" />
			),
			navigationOptions: {
				tabBarLabel: 'Express Bus',
				tabBarIcon: TabBarIcon('subway'),
			},
		},

		CarlsGoBusView: {
			screen: ({navigation}) => (
				<ConnectedXyzBusView navigation={navigation} routeName={/Carls-Go/} />
			),
			navigationOptions: {
				tabBarLabel: 'CarlsGO',
				tabBarIcon: TabBarIcon('car'),
			},
		},

		BlueLineBusView: {
			screen: ({navigation}) => (
				<ConnectedXyzBusView navigation={navigation} routeName="Blue Line" />
			),
			navigationOptions: {
				tabBarLabel: 'Blue Line',
				tabBarIcon: TabBarIcon('bus'),
			},
		},

		TransportationOtherBusView: {
			screen: ConnectedXyzBusList,
		},

		TransportationOtherModesListView: {
			screen: OtherModesView,
		},
	},
	{
		navigationOptions: {
			title: 'Transportation',
		},
	},
)
<commit_msg>remove Carls-GO tab from navigation<commit_after>// @flow

import * as React from 'react'

import {TabNavigator} from '../components/tabbed-view'
import {TabBarIcon} from '../components/tabbar-icon'

import {OtherModesView} from './other-modes'
import {ConnectedXyzBusView, ConnectedXyzBusList} from './xyz'

export {ConnectedXyzBusView} from './xyz/view'
export {OtherModesDetailView} from './other-modes'
export {BusMap} from './bus'

export default TabNavigator(
	{
		ExpressLineBusView: {
			screen: ({navigation}) => (
				<ConnectedXyzBusView navigation={navigation} routeName="Express Bus" />
			),
			navigationOptions: {
				tabBarLabel: 'Express Bus',
				tabBarIcon: TabBarIcon('subway'),
			},
		},

		BlueLineBusView: {
			screen: ({navigation}) => (
				<ConnectedXyzBusView navigation={navigation} routeName="Blue Line" />
			),
			navigationOptions: {
				tabBarLabel: 'Blue Line',
				tabBarIcon: TabBarIcon('bus'),
			},
		},

		TransportationOtherBusView: {
			screen: ConnectedXyzBusList,
		},

		TransportationOtherModesListView: {
			screen: OtherModesView,
		},
	},
	{
		navigationOptions: {
			title: 'Transportation',
		},
	},
)
<|endoftext|>


<commit_before>/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */

export default {
  googleAnalyticsId: 'UA-XXXXX-X',
};
<commit_msg>add gg analytics id<commit_after>/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */

export default {
  googleAnalyticsId: 'UA-70088073-1',
};
<|endoftext|>


<commit_before>'use strict';

require('./lib/test-env.js');

const expect = require('chai').expect;
const request = require('superagent');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const serverCtrl = require('./lib/server-ctrl');
const cleanDB = require('./lib/clean-db');
const mockUser = require('./lib/user-mock');
const mockHospital = require('./lib/hospital-mock');

mongoose.Promise = Promise;

const server = require('../server');
const url = `http://localhost:${process.env.PORT}`;

const exampleHospital = {
  name: 'Seattle Childrens',
};

describe('testing hospital-router', function(){

  before(done => serverCtrl.serverUp(server, done));
  after(done => serverCtrl.serverDown(server, done));
  afterEach(done => cleanDB(done));

  describe('testing POST /api/hospital', function(){

    describe('testing valid POST request', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 200', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          if(err) return done(err);
          expect(res.status).to.equal(200);
          expect(res.body.name).to.equal(exampleHospital.name);
          done();
        });
      });
    });

    describe('testing POST request with invalid body', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 400', (done) => {
        request.post(`${url}/api/hospital`)
        .send('{youshallnotpass')
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(400);
          done();
        });
      });
    });

    describe('testing POST request with invalid token', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 401', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: 'Bearer badtoken'})
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    });
  });

  describe('testing DELETE /api/hospital', function(){

    describe('testing valid DELETE request', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 204', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          if(err) return done(err);
          expect(res.status).to.equal(204);
          done();
        });
      });
    });
  });
});
<commit_msg>POST 400 test passing for no body hospital router test<commit_after>'use strict';

require('./lib/test-env.js');

const expect = require('chai').expect;
const request = require('superagent');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const serverCtrl = require('./lib/server-ctrl');
const cleanDB = require('./lib/clean-db');
const mockUser = require('./lib/user-mock');
const mockHospital = require('./lib/hospital-mock');

mongoose.Promise = Promise;

const server = require('../server');
const url = `http://localhost:${process.env.PORT}`;

const exampleHospital = {
  name: 'Seattle Childrens',
};

describe('testing hospital-router', function(){

  before(done => serverCtrl.serverUp(server, done));
  after(done => serverCtrl.serverDown(server, done));
  afterEach(done => cleanDB(done));

  describe('testing POST /api/hospital', function(){

    describe('testing valid POST request', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 200', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          if(err) return done(err);
          expect(res.status).to.equal(200);
          expect(res.body.name).to.equal(exampleHospital.name);
          done();
        });
      });
    });

    describe('testing POST request with invalid body', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 400', (done) => {
        request.post(`${url}/api/hospital`)
        .send('{youshallnotpass')
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(400);
          done();
        });
      });
    });

    describe('testing POST request with no body', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 400', (done) => {
        request.post(`${url}/api/hospital`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res) => {
          expect(res.status).to.equal(400);
          done();
        });
      });
    });

    describe('testing POST request with invalid token', function(){

      before(done => mockUser.call(this, done));

      it('should return a status code of 401', (done) => {
        request.post(`${url}/api/hospital`)
        .send(exampleHospital)
        .set({Authorization: 'Bearer badtoken'})
        .end((err, res) => {
          expect(res.status).to.equal(401);
          done();
        });
      });
    });
  });

  describe('testing DELETE /api/hospital', function(){

    describe('testing valid DELETE request', function(){

      before(done => mockUser.call(this, done));
      before(done => mockHospital.call(this, done));

      it('should return a status code of 204', (done) => {
        request.delete(`${url}/api/hospital/${this.tempHospital._id}`)
        .set({Authorization: `Bearer ${this.tempToken}`})
        .end((err, res)=> {
          if(err) return done(err);
          expect(res.status).to.equal(204);
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var config= (function(){
    // public methods
    function getGitlabPath(){
        return localStorage.gitlabPath || "http://example.com/";
    }

    function getApiPath(){
        return localStorage.apiPath || "http://example.com/api/v3/";
    }

    function getPrivateToken(){
        return localStorage.privateToken || "";
    }

    function getPollingSecond(){
        return localStorage.pollingSecond || 60;
    }

    function getProject(project_id){
        project_id = parseInt(project_id);
        var projects = getProjects();
        return projects[project_id] || {name: "", events: {}};
    }

    function getProjects(){
        return JSON.parse(localStorage.projects || "{}");
    }

    function getActiveProjects(){
        var active_projects = {};
        $.each(getProjects(), function(project_id, project){
            if(isActive(project.events)){
                active_projects[project_id] = project;
            }
        });
        return active_projects;
    }

    function getMaxEventCount(){
        return localStorage.maxEventCount || 100;
    }

    function getMaxNotificationCount(){
        return localStorage.maxNotificationCount || 10;
    }

    function getNewMarkMinute(){
        return localStorage.newMarkMinute || 10;
    }

    function setRecentEvent(project_id, recent_event){
        var recentEventHashes = getRecentEventHashes();
        recentEventHashes[project_id] = {
            hash: util.calcHash(recent_event),
            created_at: new Date()
        };
        setRecentEventHashes(recentEventHashes);
    }

    function getRecentEventHash(project_id){
        var obj = getRecentEventHashes()[project_id];
        return obj ? obj.hash : null;
    }

    function getNotifiedHistories(){
        return JSON.parse(localStorage.notifiedHistories || "[]");
    }

    function addNotifiedHistories(newHistories){
        // newHistories = [newest ... oldest]
        // notifiedHistories = [newest ... oldest]
        var notified_histories = getNotifiedHistories();

        // add param histories
        while(newHistories.length > 0){
            notified_histories.unshift(newHistories.pop());
        }

        // remove old histories
        while(notified_histories.length > getMaxEventCount()){
            notified_histories.pop();
        }

        localStorage.notifiedHistories = JSON.stringify(notified_histories);
    }

    // remove target history with given '_id'
    function removeNotifiedHistory(_id){
        var notified_histories = getNotifiedHistories();

        // remove target history
        $.each(notified_histories, function(index, project_event){
            if(project_event._id == _id)  {
                notified_histories.splice(index, 1);
            }
        });

        // save histories
        localStorage.notifiedHistories = JSON.stringify(notified_histories);
    }

    function clearCache(){
        localStorage.removeItem("notifiedHistories");
        localStorage.removeItem("recentEvents");
        localStorage.removeItem("recentEventHashes");
    }

    function save(args){
        util.checkArgs(args, ["gitlabPath", "privateToken", "privateToken", "pollingSecond", "maxEventCount", "maxNotificationCount", "newMarkMinute", "projects"]);

        localStorage.gitlabPath           = args.gitlabPath;
        localStorage.apiPath              = args.apiPath;
        localStorage.privateToken         = args.privateToken;
        localStorage.pollingSecond        = args.pollingSecond;
        localStorage.maxEventCount        = args.maxEventCount;
        localStorage.maxNotificationCount = args.maxNotificationCount;
        localStorage.newMarkMinute        = args.newMarkMinute;
        if (Object.keys(args.projects).length > 0) {
            localStorage.projects         = JSON.stringify(args.projects);
        }
    }

    return {
        getGitlabPath:           getGitlabPath,
        getApiPath:              getApiPath,
        getPrivateToken:         getPrivateToken,
        getPollingSecond:        getPollingSecond,
        getProject:              getProject,
        getProjects:             getProjects,
        getActiveProjects:       getActiveProjects,
        getMaxEventCount:        getMaxEventCount,
        getMaxNotificationCount: getMaxNotificationCount,
        getNewMarkMinute:        getNewMarkMinute,
        setRecentEvent:          setRecentEvent,
        getRecentEventHash:      getRecentEventHash,
        getNotifiedHistories:    getNotifiedHistories,
        addNotifiedHistories:    addNotifiedHistories,
        removeNotifiedHistory:   removeNotifiedHistory,
        clearCache:              clearCache,
        save:                    save
    };

    // private methods
    function getRecentEventHashes(){
        return JSON.parse(localStorage.recentEventHashes || "{}");
    }

    function setRecentEventHashes(recentEventHashes){
        localStorage.recentEventHashes = JSON.stringify(recentEventHashes);
    }

    function isActive(project_events){
        var events = gitlab.events();
        for(var i = 0; i < events.length; i++){
            var event = events[i];
            if(project_events[event]){
                return true;
            }
        }
        return false;
    }
}());
<commit_msg>Break $.each loop when id is found<commit_after>var config= (function(){
    // public methods
    function getGitlabPath(){
        return localStorage.gitlabPath || "http://example.com/";
    }

    function getApiPath(){
        return localStorage.apiPath || "http://example.com/api/v3/";
    }

    function getPrivateToken(){
        return localStorage.privateToken || "";
    }

    function getPollingSecond(){
        return localStorage.pollingSecond || 60;
    }

    function getProject(project_id){
        project_id = parseInt(project_id);
        var projects = getProjects();
        return projects[project_id] || {name: "", events: {}};
    }

    function getProjects(){
        return JSON.parse(localStorage.projects || "{}");
    }

    function getActiveProjects(){
        var active_projects = {};
        $.each(getProjects(), function(project_id, project){
            if(isActive(project.events)){
                active_projects[project_id] = project;
            }
        });
        return active_projects;
    }

    function getMaxEventCount(){
        return localStorage.maxEventCount || 100;
    }

    function getMaxNotificationCount(){
        return localStorage.maxNotificationCount || 10;
    }

    function getNewMarkMinute(){
        return localStorage.newMarkMinute || 10;
    }

    function setRecentEvent(project_id, recent_event){
        var recentEventHashes = getRecentEventHashes();
        recentEventHashes[project_id] = {
            hash: util.calcHash(recent_event),
            created_at: new Date()
        };
        setRecentEventHashes(recentEventHashes);
    }

    function getRecentEventHash(project_id){
        var obj = getRecentEventHashes()[project_id];
        return obj ? obj.hash : null;
    }

    function getNotifiedHistories(){
        return JSON.parse(localStorage.notifiedHistories || "[]");
    }

    function addNotifiedHistories(newHistories){
        // newHistories = [newest ... oldest]
        // notifiedHistories = [newest ... oldest]
        var notified_histories = getNotifiedHistories();

        // add param histories
        while(newHistories.length > 0){
            notified_histories.unshift(newHistories.pop());
        }

        // remove old histories
        while(notified_histories.length > getMaxEventCount()){
            notified_histories.pop();
        }

        localStorage.notifiedHistories = JSON.stringify(notified_histories);
    }

    // remove target history with given '_id'
    function removeNotifiedHistory(_id){
        var notified_histories = getNotifiedHistories();

        // remove target history
        $.each(notified_histories, function(index, project_event){
            if(project_event._id == _id)  {
                notified_histories.splice(index, 1);
                return false; // break $.each loop
            }
        });

        // save histories
        localStorage.notifiedHistories = JSON.stringify(notified_histories);
    }

    function clearCache(){
        localStorage.removeItem("notifiedHistories");
        localStorage.removeItem("recentEvents");
        localStorage.removeItem("recentEventHashes");
    }

    function save(args){
        util.checkArgs(args, ["gitlabPath", "privateToken", "privateToken", "pollingSecond", "maxEventCount", "maxNotificationCount", "newMarkMinute", "projects"]);

        localStorage.gitlabPath           = args.gitlabPath;
        localStorage.apiPath              = args.apiPath;
        localStorage.privateToken         = args.privateToken;
        localStorage.pollingSecond        = args.pollingSecond;
        localStorage.maxEventCount        = args.maxEventCount;
        localStorage.maxNotificationCount = args.maxNotificationCount;
        localStorage.newMarkMinute        = args.newMarkMinute;
        if (Object.keys(args.projects).length > 0) {
            localStorage.projects         = JSON.stringify(args.projects);
        }
    }

    return {
        getGitlabPath:           getGitlabPath,
        getApiPath:              getApiPath,
        getPrivateToken:         getPrivateToken,
        getPollingSecond:        getPollingSecond,
        getProject:              getProject,
        getProjects:             getProjects,
        getActiveProjects:       getActiveProjects,
        getMaxEventCount:        getMaxEventCount,
        getMaxNotificationCount: getMaxNotificationCount,
        getNewMarkMinute:        getNewMarkMinute,
        setRecentEvent:          setRecentEvent,
        getRecentEventHash:      getRecentEventHash,
        getNotifiedHistories:    getNotifiedHistories,
        addNotifiedHistories:    addNotifiedHistories,
        removeNotifiedHistory:   removeNotifiedHistory,
        clearCache:              clearCache,
        save:                    save
    };

    // private methods
    function getRecentEventHashes(){
        return JSON.parse(localStorage.recentEventHashes || "{}");
    }

    function setRecentEventHashes(recentEventHashes){
        localStorage.recentEventHashes = JSON.stringify(recentEventHashes);
    }

    function isActive(project_events){
        var events = gitlab.events();
        for(var i = 0; i < events.length; i++){
            var event = events[i];
            if(project_events[event]){
                return true;
            }
        }
        return false;
    }
}());
<|endoftext|>


<commit_before>"use strict";

const classNames = {};

module.exports = {

    CreateObject: className => {
        if (undefined === classNames[className]) {
            classNames[className] = require("./" + className + ".js");
        }
        return new classNames[className]();
    },

    Arguments: process.argv.slice(2),
    ScriptFullName: process.argv[1],
    Echo: text => console.log(text),
    Quit: code => process.exit(code)

};
<commit_msg>Fix arguments handling (#226)<commit_after>"use strict";

const
    classNames = {},
    argumentsArray = process.argv.slice(2),
    argumentsFunction = index => argumentsArray[index];

Object.defineProperty(argumentsFunction, "length", {
    value: argumentsArray.length,
    writable: false
});

module.exports = {

    CreateObject: className => {
        if (undefined === classNames[className]) {
            classNames[className] = require("./" + className + ".js");
        }
        return new classNames[className]();
    },

    Arguments: argumentsFunction,
    ScriptFullName: process.argv[1],
    Echo: text => console.log(text),
    Quit: code => process.exit(code)

};
<|endoftext|>