<commit_before>var utils = require('./test-utils');
var assert = require('chai').assert;
var fs = require('fs');

var temporaryDatabase;

suiteSetup(function() {
  temporaryDatabase = utils.createTemporaryDatabase();
});

suiteTeardown(function() {
  temporaryDatabase.teardown();
  temporaryDatabase = undefined;
});

function createCommonErrorResponse(errorCode, message) {
  return '<?xml version="1.0"?>\n' +
         '<Response>' +
           '<Errors>' +
             '<Error>' + errorCode +'' +
                     '<Message>' + message + '</Message></Error>' +
             '</Errors>' +
           '<RequestID></RequestID>' +
         '</Response>';
}

var XMLNS = 'http://cloudsearch.amazonaws.com/doc/2011-02-01';
var FAKE_DOMAIN_ID = '00000000000000000000000000';

suite('Configuration API', function() {
  var database;
  var server;

  setup(function() {
    database = temporaryDatabase.get();
    server = utils.setupServer(database);
  });

  teardown(function() {
    server.close();
    temporaryDatabase.clear();
  });

  test('Get, Action=DeleteDomain', function(done) {
    var path = '/?DomainName=companies&Action=DeleteDomain&Version=2011-02-01';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var expected = {
              statusCode: 200,
              body: '<?xml version="1.0"?>\n' +
                    '<DeleteDomainResponse xmlns="' + XMLNS + '">' +
                      '<DeleteDomainResult>' +
                        '<DomainStatus>' +
                          '<Created>false</Created>' +
                          '<Deleted>true</Deleted>' +
                          '<DocService>' +
                            '<Endpoint>doc-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</DocService>' +
                          '<DomainId>' + FAKE_DOMAIN_ID + '/companies</DomainId>' +
                          '<DomainName>companies</DomainName>' +
                          '<NumSearchableDocs>0</NumSearchableDocs>' +
                          '<RequiresIndexDocuments>false</RequiresIndexDocuments>' +
                          '<SearchInstanceCount>0</SearchInstanceCount>' +
                          '<SearchPartitionCount>0</SearchPartitionCount>' +
                          '<SearchService>' +
                            '<Endpoint>search-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</SearchService>' +
                        '</DomainStatus>' +
                      '</DeleteDomainResult>' +
                      '<ResponseMetadata>' +
                        '<RequestId></RequestId>' +
                      '</ResponseMetadata>' +
                    '</DeleteDomainResponse>'
            };
        assert.deepEqual(response, expected);

        var dump = database.commandSync('dump', {
              tables: 'companies'
            });
        var expected = 'table_create companies TABLE_HASH_KEY ShortText\n' +
                       'table_create companies_BigramTerms ' +
                         'TABLE_PAT_KEY|KEY_NORMALIZE ShortText ' +
                         '--default_tokenizer TokenBigram';
        assert.equal(dump, expected);

        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, Action=CreateDomain', function(done) {
    var path = '/?DomainName=companies&Action=CreateDomain&Version=2011-02-01';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var expected = {
              statusCode: 200,
              body: '<?xml version="1.0"?>\n' +
                    '<CreateDomainResponse xmlns="' + XMLNS + '">' +
                      '<CreateDomainResult>' +
                        '<DomainStatus>' +
                          '<Created>true</Created>' +
                          '<Deleted>false</Deleted>' +
                          '<DocService>' +
                            '<Endpoint>doc-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</DocService>' +
                          '<DomainId>' + FAKE_DOMAIN_ID + '/companies</DomainId>' +
                          '<DomainName>companies</DomainName>' +
                          '<NumSearchableDocs>0</NumSearchableDocs>' +
                          '<RequiresIndexDocuments>false</RequiresIndexDocuments>' +
                          '<SearchInstanceCount>0</SearchInstanceCount>' +
                          '<SearchPartitionCount>0</SearchPartitionCount>' +
                          '<SearchService>' +
                            '<Endpoint>search-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</SearchService>' +
                        '</DomainStatus>' +
                      '</CreateDomainResult>' +
                      '<ResponseMetadata>' +
                        '<RequestId></RequestId>' +
                      '</ResponseMetadata>' +
                    '</CreateDomainResponse>'
            };
        assert.deepEqual(response, expected);

        var dump = database.commandSync('dump', {
              tables: 'companies'
            });
        var expected = 'table_create companies TABLE_HASH_KEY ShortText\n' +
                       'table_create companies_BigramTerms ' +
                         'TABLE_PAT_KEY|KEY_NORMALIZE ShortText ' +
                         '--default_tokenizer TokenBigram';
        assert.equal(dump, expected);

        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, Action=DefineIndexField', function(done) {
    var path = '/?DomainName=companies&Action=CreateDomain&Version=2011-02-01';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var path = '/?DomainName=companies&IndexField.IndexFieldName=name&' +
                   'Action=DefineIndexField&Version=2011-02-01';
        return utils.get(path);
      })
      .next(function(response) {
        var expected = {
              statusCode: 200,
              body: '<?xml version="1.0"?>\n' +
                    '<DefineIndexFieldResponse xmlns="' + XMLNS + '">' +
                      '<DefineIndexFieldResult>' +
                        '<IndexField>' +
                          '<Options>' +
                            '<IndexFieldName>name</IndexFieldName>' +
                            '<IndexFieldType>text</IndexFieldType>' +
                            '<TextOptions>' +
                              '<DefaultValue/>' +
                              '<FacetEnabled>false</FacetEnabled>' +
                              '<ResultEnabled>true</ResultEnabled>' +
                            '</TextOptions>' +
                          '</Options>' +
                          '<Status>' +
                            '<CreationDate>1970-01-01T00:00:00Z</CreationDate>' +
                            '<State>RequiresIndexDocuments</State>' +
                            '<UpdateDate>1970-01-01T00:00:00Z</UpdateDate>' +
                            '<UpdateVersion>0</UpdateVersion>' +
                          '</Status>' +
                        '</IndexField>' +
                      '</DefineIndexFieldResult>' +
                      '<ResponseMetadata>' +
                        '<RequestId></RequestId>' +
                      '</ResponseMetadata>' +
                    '</DefineIndexFieldResponse>'
            };
        var actual = {
              statusCode: response.statusCode,
              body: response.body
                      .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/g,
                               '1970-01-01T00:00:00Z')
            };
        assert.deepEqual(actual, expected);

        var dump = database.commandSync('dump', {
              tables: 'companies'
            });
        var expected = 'table_create companies_BigramTerms ' +
                         'TABLE_PAT_KEY|KEY_NORMALIZE ShortText ' +
                         '--default_tokenizer TokenBigram\n' +
                       'table_create companies TABLE_HASH_KEY ShortText\n' +
                       'column_create companies name COLUMN_SCALAR ShortText\n' +
                       'column_create companies_BigramTerms companies_name ' +
                         'COLUMN_INDEX|WITH_POSITION companies name';
        assert.equal(dump, expected);

        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, no version', function(done) {
    var path = '/?Action=unknown';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var message = 'An input parameter "Version" that is mandatory for ' +
                      'processing the request is not supplied.';;
        var expected = {
              statusCode: 400,
              body: createCommonErrorResponse('MissingParameter', message)
            };
        assert.deepEqual(response, expected);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, invalid version', function(done) {
    var path = '/?Version=2011-02-02&Action=unknown';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var message = 'A bad or out-of-range value "2011-02-02" was supplied ' +
                      'for the "Version" input parameter.';
        var expected = {
              statusCode: 400,
              body: createCommonErrorResponse('InvalidParameterValue', message)
            };
        assert.deepEqual(response, expected);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, invalid action', function(done) {
    var path = '/?Version=2011-02-01&Action=unknown';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var message = 'The action unknown is not valid for this web service.';
        var expected = {
              statusCode: 400,
              body: createCommonErrorResponse('InvalidAction', message)
            };
        assert.deepEqual(response, expected);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });
});
<commit_msg>Define tables before try to delete the domain #30<commit_after>var utils = require('./test-utils');
var assert = require('chai').assert;
var fs = require('fs');

var temporaryDatabase;

suiteSetup(function() {
  temporaryDatabase = utils.createTemporaryDatabase();
});

suiteTeardown(function() {
  temporaryDatabase.teardown();
  temporaryDatabase = undefined;
});

function createCommonErrorResponse(errorCode, message) {
  return '<?xml version="1.0"?>\n' +
         '<Response>' +
           '<Errors>' +
             '<Error>' + errorCode +'' +
                     '<Message>' + message + '</Message></Error>' +
             '</Errors>' +
           '<RequestID></RequestID>' +
         '</Response>';
}

var XMLNS = 'http://cloudsearch.amazonaws.com/doc/2011-02-01';
var FAKE_DOMAIN_ID = '00000000000000000000000000';

suite('Configuration API', function() {
  var database;
  var server;

  setup(function() {
    database = temporaryDatabase.get();
    server = utils.setupServer(database);
  });

  teardown(function() {
    server.close();
    temporaryDatabase.clear();
  });

  test('Get, Action=DeleteDomain', function(done) {
    var path = '/?DomainName=companies&Action=DeleteDomain&Version=2011-02-01';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var expected = {
              statusCode: 200,
              body: '<?xml version="1.0"?>\n' +
                    '<DeleteDomainResponse xmlns="' + XMLNS + '">' +
                      '<DeleteDomainResult>' +
                        '<DomainStatus>' +
                          '<Created>false</Created>' +
                          '<Deleted>true</Deleted>' +
                          '<DocService>' +
                            '<Endpoint>doc-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</DocService>' +
                          '<DomainId>' + FAKE_DOMAIN_ID + '/companies</DomainId>' +
                          '<DomainName>companies</DomainName>' +
                          '<NumSearchableDocs>0</NumSearchableDocs>' +
                          '<RequiresIndexDocuments>false</RequiresIndexDocuments>' +
                          '<SearchInstanceCount>0</SearchInstanceCount>' +
                          '<SearchPartitionCount>0</SearchPartitionCount>' +
                          '<SearchService>' +
                            '<Endpoint>search-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</SearchService>' +
                        '</DomainStatus>' +
                      '</DeleteDomainResult>' +
                      '<ResponseMetadata>' +
                        '<RequestId></RequestId>' +
                      '</ResponseMetadata>' +
                    '</DeleteDomainResponse>'
            };
        assert.deepEqual(response, expected);

        var dump = database.commandSync('dump', {
              tables: 'companies'
            });
        var expected = 'table_create companies TABLE_HASH_KEY ShortText\n' +
                       'table_create companies_BigramTerms ' +
                         'TABLE_PAT_KEY|KEY_NORMALIZE ShortText ' +
                         '--default_tokenizer TokenBigram';
        assert.equal(dump, expected);

        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, Action=CreateDomain', function(done) {
    utils.loadDumpFile(database, __dirname + '/fixture/companies/ddl.grn');
    var path = '/?DomainName=companies&Action=CreateDomain&Version=2011-02-01';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var expected = {
              statusCode: 200,
              body: '<?xml version="1.0"?>\n' +
                    '<CreateDomainResponse xmlns="' + XMLNS + '">' +
                      '<CreateDomainResult>' +
                        '<DomainStatus>' +
                          '<Created>true</Created>' +
                          '<Deleted>false</Deleted>' +
                          '<DocService>' +
                            '<Endpoint>doc-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</DocService>' +
                          '<DomainId>' + FAKE_DOMAIN_ID + '/companies</DomainId>' +
                          '<DomainName>companies</DomainName>' +
                          '<NumSearchableDocs>0</NumSearchableDocs>' +
                          '<RequiresIndexDocuments>false</RequiresIndexDocuments>' +
                          '<SearchInstanceCount>0</SearchInstanceCount>' +
                          '<SearchPartitionCount>0</SearchPartitionCount>' +
                          '<SearchService>' +
                            '<Endpoint>search-companies-00000000000000000000000000.localhost</Endpoint>' +
                          '</SearchService>' +
                        '</DomainStatus>' +
                      '</CreateDomainResult>' +
                      '<ResponseMetadata>' +
                        '<RequestId></RequestId>' +
                      '</ResponseMetadata>' +
                    '</CreateDomainResponse>'
            };
        assert.deepEqual(response, expected);

        var dump = database.commandSync('dump', {
              tables: 'companies'
            });
        var expected = 'table_create companies TABLE_HASH_KEY ShortText\n' +
                       'table_create companies_BigramTerms ' +
                         'TABLE_PAT_KEY|KEY_NORMALIZE ShortText ' +
                         '--default_tokenizer TokenBigram';
        assert.equal(dump, expected);

        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, Action=DefineIndexField', function(done) {
    var path = '/?DomainName=companies&Action=CreateDomain&Version=2011-02-01';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var path = '/?DomainName=companies&IndexField.IndexFieldName=name&' +
                   'Action=DefineIndexField&Version=2011-02-01';
        return utils.get(path);
      })
      .next(function(response) {
        var expected = {
              statusCode: 200,
              body: '<?xml version="1.0"?>\n' +
                    '<DefineIndexFieldResponse xmlns="' + XMLNS + '">' +
                      '<DefineIndexFieldResult>' +
                        '<IndexField>' +
                          '<Options>' +
                            '<IndexFieldName>name</IndexFieldName>' +
                            '<IndexFieldType>text</IndexFieldType>' +
                            '<TextOptions>' +
                              '<DefaultValue/>' +
                              '<FacetEnabled>false</FacetEnabled>' +
                              '<ResultEnabled>true</ResultEnabled>' +
                            '</TextOptions>' +
                          '</Options>' +
                          '<Status>' +
                            '<CreationDate>1970-01-01T00:00:00Z</CreationDate>' +
                            '<State>RequiresIndexDocuments</State>' +
                            '<UpdateDate>1970-01-01T00:00:00Z</UpdateDate>' +
                            '<UpdateVersion>0</UpdateVersion>' +
                          '</Status>' +
                        '</IndexField>' +
                      '</DefineIndexFieldResult>' +
                      '<ResponseMetadata>' +
                        '<RequestId></RequestId>' +
                      '</ResponseMetadata>' +
                    '</DefineIndexFieldResponse>'
            };
        var actual = {
              statusCode: response.statusCode,
              body: response.body
                      .replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z/g,
                               '1970-01-01T00:00:00Z')
            };
        assert.deepEqual(actual, expected);

        var dump = database.commandSync('dump', {
              tables: 'companies'
            });
        var expected = 'table_create companies_BigramTerms ' +
                         'TABLE_PAT_KEY|KEY_NORMALIZE ShortText ' +
                         '--default_tokenizer TokenBigram\n' +
                       'table_create companies TABLE_HASH_KEY ShortText\n' +
                       'column_create companies name COLUMN_SCALAR ShortText\n' +
                       'column_create companies_BigramTerms companies_name ' +
                         'COLUMN_INDEX|WITH_POSITION companies name';
        assert.equal(dump, expected);

        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, no version', function(done) {
    var path = '/?Action=unknown';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var message = 'An input parameter "Version" that is mandatory for ' +
                      'processing the request is not supplied.';;
        var expected = {
              statusCode: 400,
              body: createCommonErrorResponse('MissingParameter', message)
            };
        assert.deepEqual(response, expected);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, invalid version', function(done) {
    var path = '/?Version=2011-02-02&Action=unknown';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var message = 'A bad or out-of-range value "2011-02-02" was supplied ' +
                      'for the "Version" input parameter.';
        var expected = {
              statusCode: 400,
              body: createCommonErrorResponse('InvalidParameterValue', message)
            };
        assert.deepEqual(response, expected);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });

  test('Get, invalid action', function(done) {
    var path = '/?Version=2011-02-01&Action=unknown';
    utils.get(path, {
                'Host': 'cloudsearch.localhost'
              })
      .next(function(response) {
        var message = 'The action unknown is not valid for this web service.';
        var expected = {
              statusCode: 400,
              body: createCommonErrorResponse('InvalidAction', message)
            };
        assert.deepEqual(response, expected);
        done();
      })
      .error(function(error) {
        done(error);
      });
  });
});
<|endoftext|>


<commit_before>var page = require('webpage').create(),
	server = 'http://exam.cusat.ac.in/erp5/cusat/Cusat-Hall-Ticket',
	data = 'regno1=12130024&deg_name=B.Tech&semister=8&month=September&year=2016&reg_type=Supply/Improvement&checktype=check';
page.onResourceRequested = function (request) {
    system.stderr.writeLine('= onResourceRequested()');
    system.stderr.writeLine('  request: ' + JSON.stringify(request, undefined, 4));
};

page.onResourceReceived = function(response) {
    system.stderr.writeLine('= onResourceReceived()' );
    system.stderr.writeLine('  id: ' + response.id + ', stage: "' + response.stage + '", response: ' + JSON.stringify(response));
};

page.onLoadStarted = function() {
    system.stderr.writeLine('= onLoadStarted()');
    var currentUrl = page.evaluate(function() {
        return window.location.href;
    });
    system.stderr.writeLine('  leaving url: ' + currentUrl);
};

page.onLoadFinished = function(status) {
    system.stderr.writeLine('= onLoadFinished()');
    system.stderr.writeLine('  status: ' + status);
};

page.onNavigationRequested = function(url, type, willNavigate, main) {
    system.stderr.writeLine('= onNavigationRequested');
    system.stderr.writeLine('  destination_url: ' + url);
    system.stderr.writeLine('  type (cause): ' + type);
    system.stderr.writeLine('  will navigate: ' + willNavigate);
    system.stderr.writeLine('  from page\'s main frame: ' + main);
};

page.onResourceError = function(resourceError) {
    system.stderr.writeLine('= onResourceError()');
    system.stderr.writeLine('  - unable to load url: "' + resourceError.url + '"');
    system.stderr.writeLine('  - error code: ' + resourceError.errorCode + ', description: ' + resourceError.errorString );
};

page.onError = function(msg, trace) {
    system.stderr.writeLine('= onError()');
    var msgStack = ['  ERROR: ' + msg];
    if (trace) {
        msgStack.push('  TRACE:');
        trace.forEach(function(t) {
            msgStack.push('    -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
        });
    }
    system.stderr.writeLine(msgStack.join('\n'));
};
page.open(server, 'post', data, function(status) {
	console.log("Status: " + status);
	if(status === "success") {
	}
	page.render('example.pdf');
	phantom.exit();
});
<commit_msg>Server<commit_after>var page = require('webpage').create(),
	server = 'http://exam.cusat.ac.in/erp5/cusat/Cusat-Hall-Ticket',
	data = 'regno1=12130024&deg_name=B.Tech&semister=8&month=September&year=2016&reg_type=Supply/Improvement&checktype=check';

page.open(server, 'post', data, function(status) {
	console.log("Status: " + status);
	if(status === "success") {
	}
	page.render('example.pdf');
	phantom.exit();
});
<|endoftext|>


<commit_before>module.exports = function (app) {

  var jwt = require('express-jwt')({secret: app.secret});

  var Users = require('./routes/r_user')(app)
  var Orders = require('./routes/r_orders')(app)

  // User login
  app.post('/api/users/login', Users.login);
  // User registration
  app.post('/api/users', Users.create);

  // Only if User logged in
  app.get('/api/orders/:id', jwt, Orders.getById);
  // Only if User logged in
  app.get('/api/users/self/orders', jwt, Orders.getOrders);
  // Only if User logged in
  app.post('/api/orders', jwt, Orders.create);

}<commit_msg>Added error handling for jwt errors<commit_after>module.exports = function (app) {

  var jwt = require('express-jwt')({secret: app.secret});

  var Users = require('./routes/r_user')(app);
  var Orders = require('./routes/r_orders')(app);
  var util = require('./util');

  // User login
  app.post('/api/users/login', Users.login);
  // User registration
  app.post('/api/users', Users.create);

  // Only if User logged in
  app.get('/api/orders/:id', jwt, Orders.getById);
  // Only if User logged in
  app.get('/api/users/self/orders', jwt, Orders.getOrders, util.sendAuthError);
  // Only if User logged in
  app.post('/api/users/self/orders', jwt, Orders.create,  util.sendAuthError);

}<|endoftext|>


<commit_before>define("sand", [], function(){

	var box_id = 0;

	/**
	 * Box constructor, sets up an empty box and registers the event handlers.
	 */
    var Box = function (){
		this.domain = null;
		this.iframe = null;
		this.boxframe = null;
		this.listeners = {};
		this.queue = [];
		this.loaded = false;
		this.box_id = box_id++;
		this.callback_id = 0;
		var reference = this;
		var handler = function(event){
            if (event.origin == reference.domain) {
				reference.handle(event.data);
			}
		};
		if (window.addEventListener) {
			window.addEventListener('message', handler, false);
		}
		else {
			window.attachEvent('onmessage', handler);
		}
    };

	/**
	 * Sets the boxframe to a window reference, can be used for example with window.parent.
	 */
	Box.prototype.loadParent = function(domain){
		this.domain = domain;
		this.iframe = null;
		this.loaded = true;
		this.boxframe = window.parent;
		this.sendRaw('box-loaded');
	};

	/**
	 * Loads the iframe for a given URL, this window will be the boxframe
	 */
	Box.prototype.loadFrame = function(domain, url){
		if(this.iframe == null){
			this.domain = domain;
			this.iframe = document.createElement('iframe');
			this.iframe.setAttribute('src', url);
			this.iframe.style.width = '0px';
			this.iframe.style.height = '0px';
			this.iframe.style.border = 'none';
			document.body.appendChild(this.iframe);
			this.boxframe = this.iframe.contentWindow;
            var reference = this;
            this.iframe.onload = function(){
                reference.sendRaw('box-loaded');
            };
		}
	};

	/**
	 * Reloads the iframe
	 */
	Box.prototype.reload = function(){
		this.loaded = false;
		var current = this.iframe.src;
		this.iframe.src = 'about:blank';
		this.iframe.src = current;
		this.boxframe = this.iframe.contentWindow;
	};

	/**
	 * Handles incoming messages that match the *box's domain.
	 */
	Box.prototype.handle = function (message) {
        if(this.loaded){
			var reference = this;
			// if the message starts with box-callback
			if(message.type == 'box-callback'){
				var receivers = this.listeners[message.data.subtype];
				var callback = function(data){
					reference.sendRaw(message.data.id, data);
				};
				for(var receivers_index in receivers){
					receivers[receivers_index](message.data.subdata, callback);
				}

			}
            var receivers = this.listeners[message.type];
            for(var receivers_index in receivers){
                receivers[receivers_index](message.data);
            }
		}
        else {
			if (message.type == 'box-loaded') {
			    this.loaded = true;
				for (var queue_index in this.queue) {
					var item = this.queue[queue_index];
					this.sendRaw(item.type, item.data);
				}
				this.queue = [];
			}
		}
	};

	/**
	 * Registers a listener for a given type.
	 */
	Box.prototype.addListener = function (type, listener) {
		this.listeners[type] = this.listeners[type] || [];
		this.listeners[type].push(listener);
	};

	/**
	 * Removes one instance of a listener for a given type.
	 */
	Box.prototype.removeListener = function (type, listener) {
		this.listeners[type] = this.listeners[type] || [];
		var index = this.listeners[type].indexOf(listener);
		this.listeners.splice(index, 1);
		if(this.listeners.length == 0){
			this.removeListeners(type);
		}
	};

	/**
	 * Removes all listeners for a given type.
	 */
	Box.prototype.removeListeners = function (type) {
		delete this.listeners[type];
	};

	/**
	 * Sends a message to the boxframe.
	 *
	 * When a box is not yet loaded, messages are queued up, and dispatched when the box sends a box-loaded message.
	 */
	Box.prototype.sendRaw = function (type, data) {
		var message = {
			'type': type,
			'data': data
		};
        if(!this.loaded){
			this.queue.push(message);
		}
		else{
			this.boxframe.postMessage(message, '*');
		}
	};

	/**
	 * Generates a new callback Id
	 */
	Box.prototype.newId = function(){
		this.callback_id++;
		return "box-callback:" + this.box_id + ":" + this.callback_id;
	};

	Box.prototype.send = function(type, data){
		this.sendRaw('box-message', {
			subtype: type,
			subdata: data
		});
	};

	/**
	 * Enables the boxframe to respond directly to a message and respond in the callback.
	 */
	Box.prototype.sendCallback = function(type, data, callback, permanent) {
		var reference = this;
		var identifier = this.newId();
		this.addListener(identifier, function(data, recallback){
			if(!(permanent === true)){
				reference.removeListeners(identifier);
			}
			callback(data, recallback);
		});
		this.sendRaw('box-callback', {
			id: identifier,
			subtype: type,
			subdata: data
		});
	};

    return Box;

});
<commit_msg>Update sand.js<commit_after>define("sand", [], function(){

	var box_id = 0;

	/**
	 * Box constructor, sets up an empty box and registers the event handlers.
	 */
	var Box = function (){
		this.domain = null;
		this.iframe = null;
		this.boxframe = null;
		this.listeners = {};
		this.queue = [];
		this.loaded = false;
		this.box_id = box_id++;
		this.callback_id = 0;
		var reference = this;
		var handler = function(event){
			if (event.origin == reference.domain) {
				reference.handle(event.data);
			}
		};
		if (window.addEventListener) {
			window.addEventListener('message', handler, false);
		}
		else {
			window.attachEvent('onmessage', handler);
		}
	};

	/**
	 * Sets the boxframe to a window reference, can be used for example with window.parent.
	 */
	Box.prototype.loadParent = function(domain){
		this.domain = domain;
		this.iframe = null;
		this.loaded = true;
		this.boxframe = window.parent;
		this.sendRaw('box-loaded');
	};

	/**
	 * Loads the iframe for a given URL, this window will be the boxframe
	 */
	Box.prototype.loadFrame = function(domain, url){
		if(this.iframe == null){
			this.domain = domain;
			this.iframe = document.createElement('iframe');
			this.iframe.setAttribute('src', url);
			this.iframe.style.width = '0px';
			this.iframe.style.height = '0px';
			this.iframe.style.border = 'none';
			document.body.appendChild(this.iframe);
			this.boxframe = this.iframe.contentWindow;
			var reference = this;
			this.iframe.onload = function(){
				reference.sendRaw('box-loaded');
			};
		}
	};

	/**
	 * Reloads the iframe
	 */
	Box.prototype.reload = function(){
		this.loaded = false;
		var current = this.iframe.src;
		this.iframe.src = 'about:blank';
		this.iframe.src = current;
		this.boxframe = this.iframe.contentWindow;
	};

	/**
	 * Handles incoming messages that match the *box's domain.
	 */
	Box.prototype.handle = function (message) {
		if(this.loaded){
			var reference = this;
			// if the message starts with box-callback
			if(message.type == 'box-callback'){
				var receivers = this.listeners[message.data.subtype];
				var callback = function(data){
					reference.sendRaw(message.data.id, data);
				};
				for(var receivers_index in receivers){
					receivers[receivers_index](message.data.subdata, callback);
				}

			}
			var receivers = this.listeners[message.type];
			for(var receivers_index in receivers){
				receivers[receivers_index](message.data);
			}
		}
		else {
			if (message.type == 'box-loaded') {
				this.loaded = true;
				for (var queue_index in this.queue) {
					var item = this.queue[queue_index];
					this.sendRaw(item.type, item.data);
				}
				this.queue = [];
			}
		}
	};

	/**
	 * Registers a listener for a given type.
	 */
	Box.prototype.addListener = function (type, listener) {
		this.listeners[type] = this.listeners[type] || [];
		this.listeners[type].push(listener);
	};

	/**
	 * Removes one instance of a listener for a given type.
	 */
	Box.prototype.removeListener = function (type, listener) {
		this.listeners[type] = this.listeners[type] || [];
		var index = this.listeners[type].indexOf(listener);
		this.listeners.splice(index, 1);
		if(this.listeners.length == 0){
			this.removeListeners(type);
		}
	};

	/**
	 * Removes all listeners for a given type.
	 */
	Box.prototype.removeListeners = function (type) {
		delete this.listeners[type];
	};

	/**
	 * Sends a message to the boxframe.
	 *
	 * When a box is not yet loaded, messages are queued up, and dispatched when the box sends a box-loaded message.
	 */
	Box.prototype.sendRaw = function (type, data) {
		var message = {
			'type': type,
			'data': data
		};
		if(!this.loaded){
			this.queue.push(message);
		}
		else{
			this.boxframe.postMessage(message, '*');
		}
	};

	/**
	 * Generates a new callback Id
	 */
	Box.prototype.newId = function(){
		this.callback_id++;
		return "box-callback:" + this.box_id + ":" + this.callback_id;
	};

	Box.prototype.send = function(type, data){
		this.sendRaw('box-message', {
			subtype: type,
			subdata: data
		});
	};

	/**
	 * Enables the boxframe to respond directly to a message and respond in the callback.
	 */
	Box.prototype.sendCallback = function(type, data, callback, permanent) {
		var reference = this;
		var identifier = this.newId();
		this.addListener(identifier, function(data, recallback){
			if(!(permanent === true)){
				reference.removeListeners(identifier);
			}
			callback(data, recallback);
		});
		this.sendRaw('box-callback', {
			id: identifier,
			subtype: type,
			subdata: data
		});
	};

	return Box;

});
<|endoftext|>


<commit_before>'use strict';

var get = easyGet;
var set = easySet;

if (document.selection && document.selection.createRange) {
  get = hardGet;
  set = hardSet;
}

function easyGet (el) {
  return {
    start: el.selectionStart,
    end: el.selectionEnd
  };
}

function hardGet (el) {
  var active = document.activeElement;
  if (active !== el) {
    el.focus();
  }

  var range = document.selection.createRange();
  var bookmark = range.getBookmark();
  var original = el.value;
  var marker = getUniqueMarker(original);
  var parent = range.parentElement();
  if (parent === null || !inputs(parent)) {
    return result(0, 0);
  }
  range.text = marker + range.text + marker;

  var contents = el.value;

  el.value = original;
  range.moveToBookmark(bookmark);
  range.select();

  return result(contents.indexOf(marker), contents.lastIndexOf(marker) - marker.length);

  function result (start, end) {
    if (active !== el) { // don't disrupt pre-existing state
      if (active) {
        active.focus();
      } else {
        el.blur();
      }
    }
    return { start: start, end: end };
  }
}

function getUniqueMarker (contents) {
  var marker;
  do {
    marker = '@@marker.' + Math.random() * new Date();
  } while (contents.indexOf(marker) !== -1);
  return marker;
}

function inputs (el) {
  return ((el.tagName === 'INPUT' && el.type === 'text') || el.tagName === 'TEXTAREA');
}

function easySet (el, p) {
  el.selectionStart = parse(el, p.start);
  el.selectionEnd = parse(el, p.end);
}

function hardSet (el, p) {
  var range = el.createTextRange();

  if (p.start === 'end' && p.end === 'end') {
    range.collapse(false);
    range.select();
  } else {
    range.collapse(true);
    range.moveEnd('character', parse(el, p.end));
    range.moveStart('character', parse(el, p.start));
    range.select();
  }
}

function parse (el, value) {
  return value === 'end' ? el.value.length : value || 0;
}

function sell (el, p) {
  if (arguments.length === 2) {
    set(el, p);
  }
  return get(el);
}

module.exports = sell;
<commit_msg>isomorphic friendly<commit_after>'use strict';

var canUseDOM = !!(
  typeof window !== 'undefined' &&
  window.document &&
  window.document.createElement
);

var get = easyGet;
var set = easySet;

if (canUseDOM && document.selection && document.selection.createRange) {
  get = hardGet;
  set = hardSet;
}

function easyGet (el) {
  return {
    start: el.selectionStart,
    end: el.selectionEnd
  };
}

function hardGet (el) {
  var active = document.activeElement;
  if (active !== el) {
    el.focus();
  }

  var range = document.selection.createRange();
  var bookmark = range.getBookmark();
  var original = el.value;
  var marker = getUniqueMarker(original);
  var parent = range.parentElement();
  if (parent === null || !inputs(parent)) {
    return result(0, 0);
  }
  range.text = marker + range.text + marker;

  var contents = el.value;

  el.value = original;
  range.moveToBookmark(bookmark);
  range.select();

  return result(contents.indexOf(marker), contents.lastIndexOf(marker) - marker.length);

  function result (start, end) {
    if (active !== el) { // don't disrupt pre-existing state
      if (active) {
        active.focus();
      } else {
        el.blur();
      }
    }
    return { start: start, end: end };
  }
}

function getUniqueMarker (contents) {
  var marker;
  do {
    marker = '@@marker.' + Math.random() * new Date();
  } while (contents.indexOf(marker) !== -1);
  return marker;
}

function inputs (el) {
  return ((el.tagName === 'INPUT' && el.type === 'text') || el.tagName === 'TEXTAREA');
}

function easySet (el, p) {
  el.selectionStart = parse(el, p.start);
  el.selectionEnd = parse(el, p.end);
}

function hardSet (el, p) {
  var range = el.createTextRange();

  if (p.start === 'end' && p.end === 'end') {
    range.collapse(false);
    range.select();
  } else {
    range.collapse(true);
    range.moveEnd('character', parse(el, p.end));
    range.moveStart('character', parse(el, p.start));
    range.select();
  }
}

function parse (el, value) {
  return value === 'end' ? el.value.length : value || 0;
}

function sell (el, p) {
  if (arguments.length === 2) {
    set(el, p);
  }
  return get(el);
}

module.exports = sell;
<|endoftext|>


<commit_before>import Ember from "ember";
export default Ember.Mixin.create({
    defaultCapabilities: {
        admin: [
            'User Administrator',
            'System Administrator'
        ],
        appointments: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_appointment: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_charge: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_diagnosis: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        add_medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        add_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_patient: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_pricing: [
            'Data Entry',
            'Finance',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_pricing_profile:  [
            'Data Entry',
            'Finance',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_lab: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Lab Technician',
            'System Administrator'
        ],
        add_imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_request: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        add_inventory_item: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_purchase: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_invoice: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_payment: [
            'Cashier',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_procedure: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        add_socialwork: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_user: [
            'User Administrator',
            'System Administrator'
        ],
        add_visit: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_vitals: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        adjust_inventory_location: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        billing: [
            'Hospital Administrator',
            'Finance',
            'Finance Manager',
            'System Administrator'
        ],
        complete_imaging: [
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        complete_lab: [
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_appointment: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_diagnosis: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_inventory_item: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_inventory_purchase: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_imaging: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_invoice: [
            'Business Office',
            'Hospital Administrator',
            'System Administrator'
        ],
        delete_lab: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_medication: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_patient: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_pricing: [
            'Finance',
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_pricing_profile:  [
            'Finance',
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_procedure: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        delete_socialwork: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_vitals: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        delete_visit: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_user: [
            'User Administrator',
            'System Administrator'
        ],
        edit_invoice: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        fulfill_inventory: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        fulfill_medication: [
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        invoices: [
            'Hospital Administrator',
            'Finance',
            'Finance Manager',
            'System Administrator'
        ],
        labs: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        inventory: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        override_invoice: [
            'Business Office',
            'Hospital Administrator',
            'System Administrator'
        ],
        query_db: [
            'System Administrator'
        ],
        patients: [
            'Business Office',
            'Data Entry',
            'Doctor',
            'Finance',
            'Finance Manager',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        pricing: [
            'Data Entry',
            'Finance',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        visits: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse Manager',
            'Nurse',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        update_config: [
            'System Administrator'
        ],
        users: [
            'User Administrator',
            'System Administrator'
        ]

    },

    _getUserSessionVars: function() {
        var session = this.get('session');
        if (!Ember.isEmpty(session) && session.isAuthenticated) {
            var sessionVars = session.store.restore();
            return sessionVars;
        }
    },

    currentUserCan: function(capability) {
        var sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars) && !Ember.isEmpty(sessionVars.role)) {
            var capabilities = this.get('defaultCapabilities'),
                supportedRoles = capabilities[capability];
            if (!Ember.isEmpty(supportedRoles)) {
                return supportedRoles.contains(sessionVars.role);
            }
        }
        return false;
    },

    /**
     * Returns the display name of the user or the username if
     * the display name is not set or if the username is explictly requested.
     * @param {boolean} returnUserName if true, always return the username instead
     * of the display name even if the display name is set.
     */
    getUserName: function(returnUserName) {
        var returnName,
            sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars)) {
            if (returnUserName) {
                returnName = sessionVars.name;
            } else if (!Ember.isEmpty(sessionVars.displayName)) {
                returnName = sessionVars.displayName;
            } else if (!Ember.isEmpty(sessionVars.name)) {
                returnName = sessionVars.name;
            }
        }
        return returnName;
    }
});<commit_msg>Gave Finance access to appointments<commit_after>import Ember from "ember";
export default Ember.Mixin.create({
    defaultCapabilities: {
        admin: [
            'User Administrator',
            'System Administrator'
        ],
        appointments: [
            'Data Entry',
            'Finance',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_appointment: [
            'Data Entry',
            'Finance',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_charge: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_diagnosis: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        add_medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        add_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_patient: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_pricing: [
            'Data Entry',
            'Finance',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_pricing_profile:  [
            'Data Entry',
            'Finance',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_lab: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Lab Technician',
            'System Administrator'
        ],
        add_imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_request: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        add_inventory_item: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_inventory_purchase: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_invoice: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_payment: [
            'Cashier',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        add_procedure: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        add_socialwork: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_user: [
            'User Administrator',
            'System Administrator'
        ],
        add_visit: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        add_vitals: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        adjust_inventory_location: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        billing: [
            'Hospital Administrator',
            'Finance',
            'Finance Manager',
            'System Administrator'
        ],
        complete_imaging: [
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        complete_lab: [
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_appointment: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_diagnosis: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_inventory_item: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_inventory_purchase: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_imaging: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_invoice: [
            'Business Office',
            'Hospital Administrator',
            'System Administrator'
        ],
        delete_lab: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_medication: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_photo: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_patient: [
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'System Administrator'
        ],
        delete_pricing: [
            'Finance',
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_pricing_profile:  [
            'Finance',
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        delete_procedure: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'System Administrator'
        ],
        delete_socialwork: [
            'Data Entry',
            'Hospital Administrator',
            'Medical Records Officer',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_vitals: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'System Administrator'
        ],
        delete_visit: [
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        delete_user: [
            'User Administrator',
            'System Administrator'
        ],
        edit_invoice: [
            'Data Entry',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        fulfill_inventory: [
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        fulfill_medication: [
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        imaging: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Imaging Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        invoices: [
            'Hospital Administrator',
            'Finance',
            'Finance Manager',
            'System Administrator'
        ],
        labs: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Lab Technician',
            'Medical Records Officer',
            'System Administrator'
        ],
        medication: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Pharmacist',
            'System Administrator'
        ],
        inventory: [
            'Data Entry',
            'Hospital Administrator',
            'Inventory Manager',
            'Medical Records Officer',
            'Nurse Manager',
            'Pharmacist',
            'System Administrator'
        ],
        override_invoice: [
            'Business Office',
            'Hospital Administrator',
            'System Administrator'
        ],
        query_db: [
            'System Administrator'
        ],
        patients: [
            'Business Office',
            'Data Entry',
            'Doctor',
            'Finance',
            'Finance Manager',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse',
            'Nurse Manager',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        pricing: [
            'Data Entry',
            'Finance',
            'Business Office',
            'Hospital Administrator',
            'Medical Records Officer',
            'System Administrator'
        ],
        visits: [
            'Data Entry',
            'Doctor',
            'Hospital Administrator',
            'Medical Records Officer',
            'Nurse Manager',
            'Nurse',
            'Patient Administration',
            'Social Worker',
            'System Administrator'
        ],
        update_config: [
            'System Administrator'
        ],
        users: [
            'User Administrator',
            'System Administrator'
        ]

    },

    _getUserSessionVars: function() {
        var session = this.get('session');
        if (!Ember.isEmpty(session) && session.isAuthenticated) {
            var sessionVars = session.store.restore();
            return sessionVars;
        }
    },

    currentUserCan: function(capability) {
        var sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars) && !Ember.isEmpty(sessionVars.role)) {
            var capabilities = this.get('defaultCapabilities'),
                supportedRoles = capabilities[capability];
            if (!Ember.isEmpty(supportedRoles)) {
                return supportedRoles.contains(sessionVars.role);
            }
        }
        return false;
    },

    /**
     * Returns the display name of the user or the username if
     * the display name is not set or if the username is explictly requested.
     * @param {boolean} returnUserName if true, always return the username instead
     * of the display name even if the display name is set.
     */
    getUserName: function(returnUserName) {
        var returnName,
            sessionVars = this._getUserSessionVars();
        if (!Ember.isEmpty(sessionVars)) {
            if (returnUserName) {
                returnName = sessionVars.name;
            } else if (!Ember.isEmpty(sessionVars.displayName)) {
                returnName = sessionVars.displayName;
            } else if (!Ember.isEmpty(sessionVars.name)) {
                returnName = sessionVars.name;
            }
        }
        return returnName;
    }
});<|endoftext|>


<commit_before>Ext.define('doweown.model.WorldCatBooks', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
                {name: 'title',         type: 'string', mapping: 'title'},
                {name: 'author',        type: 'string', mapping: 'author'},
                {name: 'publisher',     type: 'string', mapping: 'publisher'},
		{name: 'date',          type: 'string', mapping: 'date'},
		{name: 'totalLibCount',	type: 'string', mapping: 'totalLibCount'},
		{name: 'ISBN', mapping: 'ISBN'},
		{name: 'library', mapping: 'library'}
        ]
    }
});
<commit_msg>added thumbnail<commit_after>Ext.define('doweown.model.WorldCatBooks', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
                {name: 'title',         type: 'string', mapping: 'title'},
                {name: 'author',        type: 'string', mapping: 'author'},
                {name: 'publisher',     type: 'string', mapping: 'publisher'},
		{name: 'date',          type: 'string', mapping: 'date'},
		{name: 'thumbnail',     type: 'string', mapping: 'thumbnail'},
		{name: 'ISBN', mapping: 'ISBN'},
		{name: 'totalLibCount',	type: 'string', mapping: 'totalLibCount'},
		{name: 'library', mapping: 'library'}
        ]
    }
});
<|endoftext|>


<commit_before>/* eslint-disable prefer-destructuring */
import { createSelector, createStructuredSelector } from 'reselect';
import moment from 'moment';
import { format } from 'd3-format';
import isEmpty from 'lodash/isEmpty';
import sortBy from 'lodash/sortBy';
import orderBy from 'lodash/orderBy';
import sumBy from 'lodash/sumBy';
import groupBy from 'lodash/groupBy';
import max from 'lodash/max';
import min from 'lodash/min';

import {
  getStatsData,
  getDatesData,
  getPeriodVariance,
  getChartConfig,
} from 'components/widgets/utils/data';

const getAlerts = (state) => state.data && state.data.alerts;
const getLatest = (state) => state.data && state.data.latest;
const getColors = (state) => state.colors || null;
const getCompareYear = (state) => state.settings.compareYear || null;
const getDataset = (state) => state.settings.dataset || null;
const getStartIndex = (state) => state.settings.startIndex || 0;
const getEndIndex = (state) => state.settings.endIndex || null;
const getSentences = (state) => state.sentences || null;
const getLocationName = (state) => state.locationLabel;
const getLang = (state) => state.lang || null;
const getOptionsSelected = (state) => state.optionsSelected;
const getIndicator = (state) => state.indicator;

const MINGAP = 4;

export const getData = createSelector(
  [getAlerts, getLatest],
  (data, latest) => {
    if (!data || isEmpty(data)) return null;
    const parsedData = data.map((d) => ({
      ...d,
      count: d.alert__count,
      week: parseInt(d.alert__week, 10),
      year: parseInt(d.alert__year, 10),
    }));
    const groupedByYear = groupBy(sortBy(parsedData, ['year', 'week']), 'year');
    const hasAlertsByYears = Object.values(groupedByYear).reduce(
      (acc, next) => {
        const { year } = next[0];
        return {
          ...acc,
          [year]: next.some((item) => item.alerts > 0),
        };
      },
      {}
    );

    const dataYears = Object.keys(hasAlertsByYears).filter(
      (key) => hasAlertsByYears[key] === true
    );
    const minYear = Math.min(...dataYears.map((el) => parseInt(el, 10)));
    const startYear =
      minYear === moment().year() ? moment().year() - 1 : minYear;

    const years = [];
    const latestWeek = moment(latest);
    const lastWeek = {
      isoWeek: latestWeek.isoWeek(),
      year: latestWeek.year(),
    };

    for (let i = startYear; i <= lastWeek.year; i += 1) {
      years.push(i);
    }

    const yearLengths = {};
    years.forEach((y) => {
      if (lastWeek.year === y) {
        yearLengths[y] = lastWeek.isoWeek;
      } else if (moment(`${y}-12-31`).isoWeek() === 1) {
        yearLengths[y] = moment(`${y}-12-31`).subtract(1, 'week').isoWeek();
      } else {
        yearLengths[y] = moment(`${y}-12-31`).isoWeek();
      }
    });

    const zeroFilledData = [];

    years.forEach((d) => {
      const yearDataByWeek = groupBy(groupedByYear[d], 'week');
      for (let i = 1; i <= yearLengths[d]; i += 1) {
        zeroFilledData.push(
          yearDataByWeek[i]
            ? yearDataByWeek[i][0]
            : { count: 0, week: i, year: parseInt(d, 10) }
        );
      }
    });
    return zeroFilledData;
  }
);

export const getStats = createSelector([getData, getLatest], (data, latest) => {
  if (!data) return null;
  return getStatsData(data, moment(latest).format('YYYY-MM-DD'));
});

export const getDates = createSelector([getStats], (data) => {
  if (!data) return null;
  return getDatesData(data);
});

export const getMaxMinDates = createSelector(
  [getData, getDates],
  (data, currentData) => {
    if (!data || !currentData) return {};
    const minYear = min(data.map((d) => d.year));
    const maxYear = max(data.map((d) => d.year));

    return {
      min: minYear,
      max: maxYear,
    };
  }
);

export const getStartEndIndexes = createSelector(
  [getStartIndex, getEndIndex, getDates],
  (startIndex, endIndex, currentData) => {
    if (!currentData) {
      return {
        startIndex,
        endIndex,
      };
    }

    const start = startIndex;
    const end = endIndex || currentData.length - 1;

    return {
      startIndex: start,
      endIndex: end,
    };
  }
);

export const parseData = createSelector(
  [getData, getDates, getMaxMinDates, getCompareYear],
  (data, currentData, maxminYear, compareYear) => {
    if (!data || !currentData) return null;

    return currentData.map((d) => {
      const yearDifference = maxminYear.max - d.year;
      const { week } = d;

      if (compareYear) {
        const parsedCompareYear = compareYear - yearDifference;

        const compareWeek = data.find(
          (dt) => dt.year === parsedCompareYear && dt.week === week
        );

        return {
          ...d,
          compareYear: parsedCompareYear,
          compareCount: compareWeek ? compareWeek.count : null,
        };
      }

      return d;
    });
  }
);

export const parseBrushedData = createSelector(
  [parseData, getStartEndIndexes],
  (data, indexes) => {
    if (!data) return null;

    const { startIndex, endIndex } = indexes;

    const start = startIndex || 0;
    const end = endIndex || data.length - 1;

    return data.slice(start, end + 1);
  }
);

export const getLegend = createSelector(
  [parseBrushedData, getColors, getCompareYear],
  (data, colors, compareYear) => {
    if (!data) return {};

    const first = data[0];
    const end = data[data.length - 1];

    return {
      current: {
        label: `${moment(first.date).format('MMM YYYY')}–${moment(
          end.date
        ).format('MMM YYYY')}`,
        color: colors.main,
      },
      ...(compareYear && {
        compare: {
          label: `${moment(first.date)
            .set('year', first.compareYear)
            .format('MMM YYYY')}–${moment(end.date)
            .set('year', end.compareYear)
            .format('MMM YYYY')}`,
          color: '#49b5e3',
        },
      }),
      average: {
        label: 'Normal Range',
        color: 'rgba(85,85,85, 0.15)',
      },
      unusual: {
        label: 'Above/Below Normal Range',
        color: 'rgba(85,85,85, 0.25)',
      },
    };
  }
);

export const parseConfig = createSelector(
  [
    getLegend,
    getColors,
    getLatest,
    getMaxMinDates,
    getCompareYear,
    getDataset,
    getStartEndIndexes,
  ],
  (legend, colors, latest, maxminYear, compareYear, dataset, indexes) => {
    const { startIndex, endIndex } = indexes;

    const tooltip = [
      {
        label: 'Fire alerts in the week of:',
      },
      {
        key: 'count',
        labelKey: 'date',
        labelFormat: (value) => moment(value).format('MMM DD YYYY'),
        unit: ` ${dataset.toUpperCase()} alerts`,
        color: colors.main,
        unitFormat: (value) =>
          Number.isInteger(value) ? format(',')(value) : value,
      },
    ];

    if (compareYear) {
      tooltip.push({
        key: 'compareCount',
        labelKey: 'date',
        labelFormat: (value) => {
          const date = moment(value);
          const yearDifference = maxminYear.max - date.year();
          date.set('year', compareYear - yearDifference);

          return date.format('MMM DD YYYY');
        },
        unit: ` ${dataset.toUpperCase()} alerts`,
        color: '#49b5e3',
        nullValue: 'No data available',
        unitFormat: (value) =>
          Number.isInteger(value) ? format(',')(value) : value,
      });
    }

    return {
      ...getChartConfig(colors, moment(latest)),
      xAxis: {
        tickCount: 12,
        interval: 4,
        scale: 'point',
        tickFormatter: (t) => moment(t).format('MMM'),
        ...(typeof endIndex === 'number' &&
          typeof startIndex === 'number' &&
          endIndex - startIndex < 10 && {
            tickCount: 5,
            interval: 0,
            tickFormatter: (t) => moment(t).format('MMM-DD'),
          }),
      },
      legend,
      tooltip,
      brush: {
        width: '100%',
        height: 60,
        margin: {
          top: 0,
          right: 10,
          left: 48,
          bottom: 12,
        },
        dataKey: 'date',
        startIndex,
        endIndex,
        minimumGap: MINGAP,
        maximumGap: 0,
        config: {
          margin: {
            top: 5,
            right: 0,
            left: 42,
            bottom: 20,
          },
          yKeys: {
            lines: {
              count: {
                stroke: colors.main,
                isAnimationActive: false,
              },
              compareCount: {
                stroke: '#49b5e3',
                isAnimationActive: false,
              },
            },
          },
          xAxis: {
            hide: true,
          },
          yAxis: {
            hide: true,
          },
          cartesianGrid: {
            horizontal: false,
            vertical: false,
          },
          height: 60,
        },
      },
    };
  }
);

export const parseSentence = createSelector(
  [
    getData,
    parseData,
    getColors,
    getSentences,
    getDataset,
    getLocationName,
    getStartEndIndexes,
    getOptionsSelected,
    getLang,
    getIndicator,
  ],
  (
    raw_data,
    data,
    colors,
    sentences,
    dataset,
    location,
    indexes,
    options,
    lang,
    indicator
  ) => {
    if (!data) return null;
    const {
      highConfidence,
      allAlerts,
      highConfidenceWithInd,
      allAlertsWithInd,
    } = sentences;
    const { confidence } = options;
    const indicatorLabel =
      indicator && indicator.label ? indicator.label : null;
    const { startIndex, endIndex } = indexes;
    const start = startIndex;
    const end = endIndex || data.length - 1;

    const lastDate = data[end] || {};
    const firstDate = data[start] || {};

    const slicedData = data.filter(
      (el) => el.date >= firstDate.date && el.date <= lastDate.date
    );
    const variance = getPeriodVariance(slicedData, raw_data);

    const maxMean = max(data.map((d) => d.mean));
    const minMean = min(data.map((d) => d.mean));
    const halfMax = (maxMean - minMean) * 0.5;

    const sortedWeeks = orderBy(data, 'date');

    const minWeeks = sortedWeeks.filter((d) => d.mean <= minMean);
    const lastMinDate =
      minWeeks && minWeeks.length ? minWeeks[minWeeks.length - 1].date : 0;
    const sortedPeakWeeks = sortedWeeks.filter((d) => d.mean > halfMax);
    const seasonStartDate =
      sortedPeakWeeks.length &&
      sortedPeakWeeks.filter((d) => d.date > lastMinDate)[0].date;
    const seasonMonth = moment(seasonStartDate).format('MMMM');
    const seasonDay = parseInt(moment(seasonStartDate).format('D'), 10);

    let seasonStatement = `late ${seasonMonth}`;
    if (seasonDay <= 10) {
      seasonStatement = `early ${seasonMonth}`;
    } else if (seasonDay > 10 && seasonDay <= 20) {
      seasonStatement = `mid-${seasonMonth}`;
    }

    const total = sumBy(slicedData, 'count');
    const colorRange = colors.ramp;
    let statusColor = colorRange[8];
    const { date } = lastDate || {};

    let status = 'unusually low';
    if (variance > 2) {
      status = 'unusually high';
      statusColor = colorRange[0];
    } else if (variance <= 2 && variance > 1) {
      status = 'high';
      statusColor = colorRange[2];
    } else if (variance <= 1 && variance > -1) {
      status = 'normal';
      statusColor = colorRange[4];
    } else if (variance <= -1 && variance > -2) {
      status = 'low';
      statusColor = colorRange[6];
    }

    let sentence =
      confidence && confidence.value === 'h' ? highConfidence : allAlerts;
    if (indicator) {
      sentence =
        confidence && confidence.value === 'h'
          ? highConfidenceWithInd
          : allAlertsWithInd;
    }

    const formattedData = moment(date).format('Do of MMMM YYYY');
    const params = {
      location,
      indicator: indicatorLabel,
      date: formattedData,
      fires_season_start: seasonStatement,
      fire_season_length: sortedPeakWeeks.length,
      start_date: moment(firstDate.date).format('Do of MMMM YYYY'),
      end_date: moment(lastDate.date).format('Do of MMMM YYYY'),
      dataset_start_year: dataset === 'viirs' ? 2012 : 2001,
      dataset: dataset.toUpperCase(),
      count: {
        value: total ? format(',')(total) : 0,
        color: colors.main,
      },
      status: {
        value: status,
        color: statusColor,
      },
      lang,
    };
    return { sentence, params };
  }
);

export default createStructuredSelector({
  originalData: parseData,
  data: parseBrushedData,
  config: parseConfig,
  sentence: parseSentence,
});
<commit_msg>Remove redundant check<commit_after>/* eslint-disable prefer-destructuring */
import { createSelector, createStructuredSelector } from 'reselect';
import moment from 'moment';
import { format } from 'd3-format';
import isEmpty from 'lodash/isEmpty';
import sortBy from 'lodash/sortBy';
import orderBy from 'lodash/orderBy';
import sumBy from 'lodash/sumBy';
import groupBy from 'lodash/groupBy';
import max from 'lodash/max';
import min from 'lodash/min';

import {
  getStatsData,
  getDatesData,
  getPeriodVariance,
  getChartConfig,
} from 'components/widgets/utils/data';

const getAlerts = (state) => state.data && state.data.alerts;
const getLatest = (state) => state.data && state.data.latest;
const getColors = (state) => state.colors || null;
const getCompareYear = (state) => state.settings.compareYear || null;
const getDataset = (state) => state.settings.dataset || null;
const getStartIndex = (state) => state.settings.startIndex || 0;
const getEndIndex = (state) => state.settings.endIndex || null;
const getSentences = (state) => state.sentences || null;
const getLocationName = (state) => state.locationLabel;
const getLang = (state) => state.lang || null;
const getOptionsSelected = (state) => state.optionsSelected;
const getIndicator = (state) => state.indicator;

const MINGAP = 4;

export const getData = createSelector(
  [getAlerts, getLatest],
  (data, latest) => {
    if (!data || isEmpty(data)) return null;
    const parsedData = data.map((d) => ({
      ...d,
      count: d.alert__count,
      week: parseInt(d.alert__week, 10),
      year: parseInt(d.alert__year, 10),
    }));
    const groupedByYear = groupBy(sortBy(parsedData, ['year', 'week']), 'year');
    const hasAlertsByYears = Object.values(groupedByYear).reduce(
      (acc, next) => {
        const { year } = next[0];
        return {
          ...acc,
          [year]: next.some((item) => item.alerts > 0),
        };
      },
      {}
    );

    const dataYears = Object.keys(hasAlertsByYears).filter(
      (key) => hasAlertsByYears[key] === true
    );
    const minYear = Math.min(...dataYears.map((el) => parseInt(el, 10)));
    const startYear =
      minYear === moment().year() ? moment().year() - 1 : minYear;

    const years = [];
    const latestWeek = moment(latest);
    const lastWeek = {
      isoWeek: latestWeek.isoWeek(),
      year: latestWeek.year(),
    };

    for (let i = startYear; i <= lastWeek.year; i += 1) {
      years.push(i);
    }

    const yearLengths = {};
    years.forEach((y) => {
      if (lastWeek.year === y) {
        yearLengths[y] = lastWeek.isoWeek;
      } else if (moment(`${y}-12-31`).isoWeek() === 1) {
        yearLengths[y] = moment(`${y}-12-31`).subtract(1, 'week').isoWeek();
      } else {
        yearLengths[y] = moment(`${y}-12-31`).isoWeek();
      }
    });

    const zeroFilledData = [];

    years.forEach((d) => {
      const yearDataByWeek = groupBy(groupedByYear[d], 'week');
      for (let i = 1; i <= yearLengths[d]; i += 1) {
        zeroFilledData.push(
          yearDataByWeek[i]
            ? yearDataByWeek[i][0]
            : { count: 0, week: i, year: parseInt(d, 10) }
        );
      }
    });
    return zeroFilledData;
  }
);

export const getStats = createSelector([getData, getLatest], (data, latest) => {
  if (!data) return null;
  return getStatsData(data, moment(latest).format('YYYY-MM-DD'));
});

export const getDates = createSelector([getStats], (data) => {
  if (!data) return null;
  return getDatesData(data);
});

export const getMaxMinDates = createSelector(
  [getData, getDates],
  (data, currentData) => {
    if (!data || !currentData) return {};
    const minYear = min(data.map((d) => d.year));
    const maxYear = max(data.map((d) => d.year));

    return {
      min: minYear,
      max: maxYear,
    };
  }
);

export const getStartEndIndexes = createSelector(
  [getStartIndex, getEndIndex, getDates],
  (startIndex, endIndex, currentData) => {
    if (!currentData) {
      return {
        startIndex,
        endIndex,
      };
    }

    const start = startIndex;
    const end = endIndex || currentData.length - 1;

    return {
      startIndex: start,
      endIndex: end,
    };
  }
);

export const parseData = createSelector(
  [getData, getDates, getMaxMinDates, getCompareYear],
  (data, currentData, maxminYear, compareYear) => {
    if (!data || !currentData) return null;

    return currentData.map((d) => {
      const yearDifference = maxminYear.max - d.year;
      const { week } = d;

      if (compareYear) {
        const parsedCompareYear = compareYear - yearDifference;

        const compareWeek = data.find(
          (dt) => dt.year === parsedCompareYear && dt.week === week
        );

        return {
          ...d,
          compareYear: parsedCompareYear,
          compareCount: compareWeek ? compareWeek.count : null,
        };
      }

      return d;
    });
  }
);

export const parseBrushedData = createSelector(
  [parseData, getStartEndIndexes],
  (data, indexes) => {
    if (!data) return null;

    const { startIndex, endIndex } = indexes;

    const start = startIndex || 0;
    const end = endIndex || data.length - 1;

    return data.slice(start, end + 1);
  }
);

export const getLegend = createSelector(
  [parseBrushedData, getColors, getCompareYear],
  (data, colors, compareYear) => {
    if (!data) return {};

    const first = data[0];
    const end = data[data.length - 1];

    return {
      current: {
        label: `${moment(first.date).format('MMM YYYY')}–${moment(
          end.date
        ).format('MMM YYYY')}`,
        color: colors.main,
      },
      ...(compareYear && {
        compare: {
          label: `${moment(first.date)
            .set('year', first.compareYear)
            .format('MMM YYYY')}–${moment(end.date)
            .set('year', end.compareYear)
            .format('MMM YYYY')}`,
          color: '#49b5e3',
        },
      }),
      average: {
        label: 'Normal Range',
        color: 'rgba(85,85,85, 0.15)',
      },
      unusual: {
        label: 'Above/Below Normal Range',
        color: 'rgba(85,85,85, 0.25)',
      },
    };
  }
);

export const parseConfig = createSelector(
  [
    getLegend,
    getColors,
    getLatest,
    getMaxMinDates,
    getCompareYear,
    getDataset,
    getStartEndIndexes,
  ],
  (legend, colors, latest, maxminYear, compareYear, dataset, indexes) => {
    const { startIndex, endIndex } = indexes;

    const tooltip = [
      {
        label: 'Fire alerts in the week of:',
      },
      {
        key: 'count',
        labelKey: 'date',
        labelFormat: (value) => moment(value).format('MMM DD YYYY'),
        unit: ` ${dataset.toUpperCase()} alerts`,
        color: colors.main,
        unitFormat: (value) =>
          Number.isInteger(value) ? format(',')(value) : value,
      },
    ];

    if (compareYear) {
      tooltip.push({
        key: 'compareCount',
        labelKey: 'date',
        labelFormat: (value) => {
          const date = moment(value);
          const yearDifference = maxminYear.max - date.year();
          date.set('year', compareYear - yearDifference);

          return date.format('MMM DD YYYY');
        },
        unit: ` ${dataset.toUpperCase()} alerts`,
        color: '#49b5e3',
        nullValue: 'No data available',
        unitFormat: (value) =>
          Number.isInteger(value) ? format(',')(value) : value,
      });
    }

    return {
      ...getChartConfig(colors, moment(latest)),
      xAxis: {
        tickCount: 12,
        interval: 4,
        scale: 'point',
        tickFormatter: (t) => moment(t).format('MMM'),
        ...(typeof endIndex === 'number' &&
          typeof startIndex === 'number' &&
          endIndex - startIndex < 10 && {
            tickCount: 5,
            interval: 0,
            tickFormatter: (t) => moment(t).format('MMM-DD'),
          }),
      },
      legend,
      tooltip,
      brush: {
        width: '100%',
        height: 60,
        margin: {
          top: 0,
          right: 10,
          left: 48,
          bottom: 12,
        },
        dataKey: 'date',
        startIndex,
        endIndex,
        minimumGap: MINGAP,
        maximumGap: 0,
        config: {
          margin: {
            top: 5,
            right: 0,
            left: 42,
            bottom: 20,
          },
          yKeys: {
            lines: {
              count: {
                stroke: colors.main,
                isAnimationActive: false,
              },
              compareCount: {
                stroke: '#49b5e3',
                isAnimationActive: false,
              },
            },
          },
          xAxis: {
            hide: true,
          },
          yAxis: {
            hide: true,
          },
          cartesianGrid: {
            horizontal: false,
            vertical: false,
          },
          height: 60,
        },
      },
    };
  }
);

export const parseSentence = createSelector(
  [
    getData,
    parseData,
    getColors,
    getSentences,
    getDataset,
    getLocationName,
    getStartEndIndexes,
    getOptionsSelected,
    getLang,
    getIndicator,
  ],
  (
    raw_data,
    data,
    colors,
    sentences,
    dataset,
    location,
    indexes,
    options,
    lang,
    indicator
  ) => {
    if (!data) return null;
    const {
      highConfidence,
      allAlerts,
      highConfidenceWithInd,
      allAlertsWithInd,
    } = sentences;
    const { confidence } = options;
    const indicatorLabel =
      indicator && indicator.label ? indicator.label : null;
    const { startIndex, endIndex } = indexes;
    const start = startIndex;
    const end = endIndex || data.length - 1;

    const lastDate = data[end] || {};
    const firstDate = data[start] || {};

    const slicedData = data.filter(
      (el) => el.date >= firstDate.date && el.date <= lastDate.date
    );
    const variance = getPeriodVariance(slicedData, raw_data);

    const maxMean = max(data.map((d) => d.mean));
    const minMean = min(data.map((d) => d.mean));
    const halfMax = (maxMean - minMean) * 0.5;

    const sortedWeeks = orderBy(data, 'date');

    const minWeeks = sortedWeeks.filter((d) => d.mean <= minMean);
    const lastMinDate = minWeeks[minWeeks.length - 1].date;
    const sortedPeakWeeks = sortedWeeks.filter((d) => d.mean > halfMax);
    const seasonStartDate =
      sortedPeakWeeks.length &&
      sortedPeakWeeks.filter((d) => d.date > lastMinDate)[0].date;
    const seasonMonth = moment(seasonStartDate).format('MMMM');
    const seasonDay = parseInt(moment(seasonStartDate).format('D'), 10);

    let seasonStatement = `late ${seasonMonth}`;
    if (seasonDay <= 10) {
      seasonStatement = `early ${seasonMonth}`;
    } else if (seasonDay > 10 && seasonDay <= 20) {
      seasonStatement = `mid-${seasonMonth}`;
    }

    const total = sumBy(slicedData, 'count');
    const colorRange = colors.ramp;
    let statusColor = colorRange[8];
    const { date } = lastDate || {};

    let status = 'unusually low';
    if (variance > 2) {
      status = 'unusually high';
      statusColor = colorRange[0];
    } else if (variance <= 2 && variance > 1) {
      status = 'high';
      statusColor = colorRange[2];
    } else if (variance <= 1 && variance > -1) {
      status = 'normal';
      statusColor = colorRange[4];
    } else if (variance <= -1 && variance > -2) {
      status = 'low';
      statusColor = colorRange[6];
    }

    let sentence =
      confidence && confidence.value === 'h' ? highConfidence : allAlerts;
    if (indicator) {
      sentence =
        confidence && confidence.value === 'h'
          ? highConfidenceWithInd
          : allAlertsWithInd;
    }

    const formattedData = moment(date).format('Do of MMMM YYYY');
    const params = {
      location,
      indicator: indicatorLabel,
      date: formattedData,
      fires_season_start: seasonStatement,
      fire_season_length: sortedPeakWeeks.length,
      start_date: moment(firstDate.date).format('Do of MMMM YYYY'),
      end_date: moment(lastDate.date).format('Do of MMMM YYYY'),
      dataset_start_year: dataset === 'viirs' ? 2012 : 2001,
      dataset: dataset.toUpperCase(),
      count: {
        value: total ? format(',')(total) : 0,
        color: colors.main,
      },
      status: {
        value: status,
        color: statusColor,
      },
      lang,
    };
    return { sentence, params };
  }
);

export default createStructuredSelector({
  originalData: parseData,
  data: parseBrushedData,
  config: parseConfig,
  sentence: parseSentence,
});
<|endoftext|>


<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

// start customization here
var suites = [
	{name: "tizen/media_content"},
	{name: "tizen/alarm"},
	//{name: "tizen/notification"},
	{name: "tizen/lbs"},
	//{name: "tizen/call"},
	{name: "tizen/bluetooth"}
];

/*
these lines must be present and should not be modified.  "suites" argument to setSuites is
expected to be an array (should be an empty array at the very least in cases where population of
the suites argument is based on platform type and may result in no valid suites being added to the
argument)
*/
var init = require("init");
init.setSuites(suites);
init.start();
<commit_msg>reverted some changes<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

// start customization here
var suites = [
	{name: "tizen/media_content"},
	{name: "tizen/alarm"},
	{name: "tizen/notification"},
	{name: "tizen/lbs"},
	{name: "tizen/call"},
	{name: "tizen/bluetooth"}
];

/*
these lines must be present and should not be modified.  "suites" argument to setSuites is
expected to be an array (should be an empty array at the very least in cases where population of
the suites argument is based on platform type and may result in no valid suites being added to the
argument)
*/
var init = require("init");
init.setSuites(suites);
init.start();
<|endoftext|>


<commit_before>
import { expect } from 'chai';

const RG = require('../../../client/src/battles');
RG.Random = require('../../../client/src/random');
RG.DungeonGenerator = require('../../../client/src/dungeon-generator');

describe('DungeonGenerator', function() {
    // this.timeout(10000);
    it('generates dungeon levels', () => {
        RG.RAND.setSeed(new Date().getTime());
        const gen = new RG.DungeonGenerator();
        const conf = {
            nBigRooms: 0,
            rerunOnFailure: true
            // errorOnFailure: true
        };
        for (let i = 0; i < 5; i++) {
            const cols = RG.RAND.getUniformInt(80, 120);
            const rows = RG.RAND.getUniformInt(28, 56);
            const level = gen.create(cols, rows, conf);
            console.log('Level ' + i + ' created:');
            level.debugPrintInASCII();
            expect(level).to.exist;
        }
    });

    it('generates dungeon levels with actors/items', () => {
        RG.RAND.setSeed(new Date().getTime());
        const gen = new RG.DungeonGenerator();
        const cols = RG.RAND.getUniformInt(80, 120);
        const rows = RG.RAND.getUniformInt(28, 56);
        const conf = {};
        const level = gen.create(cols, rows, conf);

        const actors = level.getActors();
        const items = level.getItems();

        expect(actors.length).to.be.above(5);
        expect(items.length).to.be.above(5);
        level.debugPrintInASCII();

    });

});
<commit_msg>Changed num of created levels.<commit_after>
import { expect } from 'chai';

const RG = require('../../../client/src/battles');
RG.Random = require('../../../client/src/random');
RG.DungeonGenerator = require('../../../client/src/dungeon-generator');

describe('DungeonGenerator', function() {
    this.timeout(10000);

    it('generates dungeon levels', () => {
        RG.RAND.setSeed(new Date().getTime());
        const gen = new RG.DungeonGenerator();
        const conf = {
            nBigRooms: 0,
            rerunOnFailure: true
            // errorOnFailure: true
        };
        for (let i = 0; i < 2; i++) {
            const cols = RG.RAND.getUniformInt(80, 120);
            const rows = RG.RAND.getUniformInt(28, 56);
            const level = gen.create(cols, rows, conf);
            console.log('Level ' + i + ' created:');
            level.debugPrintInASCII();
            expect(level).to.exist;
        }
    });

    it('generates dungeon levels with actors/items', () => {
        RG.RAND.setSeed(new Date().getTime());
        const gen = new RG.DungeonGenerator();
        const cols = RG.RAND.getUniformInt(80, 120);
        const rows = RG.RAND.getUniformInt(28, 56);
        const conf = {};
        const level = gen.create(cols, rows, conf);

        const actors = level.getActors();
        const items = level.getItems();

        expect(actors.length).to.be.above(5);
        expect(items.length).to.be.above(5);
        level.debugPrintInASCII();

    });

});
<|endoftext|>