<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 ({
    /**
      *  Test cancel link closes datePicker and does not perform any selection of date/time.
      */
    testCancelLink : {
    	attributes : {value: "2012-09-10 11:23", format: "MM-dd-yyyy hh:mm"},
    	test : [function(cmp) {
    		var input = cmp.find("dateTimePickerTest").find("inputText").getElement();
    		$A.test.assertNotNull(input, "input not visible");

    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		$A.test.assertEquals("2012-09-10 11:23", value, "Initial value incorrect");

    		this.openDatePicker(cmp);
    	}, function(cmp) {
    		var datePicker = cmp.find("dateTimePickerTest").find("datePicker");
    		var cancelLink = datePicker.find("cancel").getElement();

    		$A.test.clickOrTouch(cancelLink);
    		$A.test.addWaitFor(false, function(){return $A.util.hasClass(datePicker.getElement(), "visible")});

    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		$A.test.assertEquals("2012-09-10 11:23", value, "Cancel was pressed value should not have changed");
    	}]
    },

    /**
      *  Test set link sets the appropriate date/time.
      */
    // TODO : @ctatlah - figure out why time is different when test runs on autobuilds
    _testSetLink : {
    	attributes : {format: "MM/dd/yyyy hh:mm"},
    	test : [function(cmp) {
    		var input = cmp.find("dateTimePickerTest").find("inputText").getElement();
    		$A.test.assertNotNull(input, "input not visible");

    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		$A.test.assertEquals(undefined, value, "Initial value incorrect");

    		this.openDatePicker(cmp);
    	}, function(cmp) {
    		var datePicker = cmp.find("dateTimePickerTest").find("datePicker");
    		var setLink = datePicker.find("set").getElement();

    		$A.test.clickOrTouch(setLink);
    		$A.test.addWaitFor(false, function(){return $A.util.hasClass(datePicker.getElement(), "visible")});

    		var expectedDate = this.getCleanDate(null, true);
    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		var setDate = this.getCleanDate(value, true);
    		$A.test.assertEquals(expectedDate, setDate, "Incorrect datetime was set.");
    	}]
    },

    /**
     * Acessibility test, making sure that any functionality added is still accessible
     */
    testAccessibile : {
    	attributes : {value: "2012-09-10 11:23", format: "MM-dd-yyyy hh:mm"},
    	        test : [function(cmp) {
    	  			this.openDatePicker(cmp);
    	    	}, function(cmp) {
    	    		$A.test.assertAccessible();
    	}]
     },

    /**
      *  If value is set for date/time when opening up dateTimePicker it opens to the date of set value.
      */
    testCalendarWithTimeValuePreSet : {
    	attributes : {value: '09-10-2012T11:23Z', format: 'MM/dd/yyyy HH:mm', timezone: 'GMT'},
    	test : function(cmp) {
		this.openDatePicker(cmp);
    		var expected = "September 2012";
    		var datepicker = cmp.find("dateTimePickerTest").find("datePicker");
    		var actual = this.getTextFromElm(datepicker);

    		$A.test.assertEquals(expected, actual, "Month year of datePicker is not valid");
    		actual = $A.util.getText($A.test.getElementByClass("selectedDate")[0]);
    		$A.test.assertEquals("10", actual, "Day of month that is not correct");

    		//Grabbing timepicker values to make sure that everything is set correctly
    		var timePicker = datepicker.find("time");
    		var hours = timePicker.find("hours").getElement().value;
    		var minutes = timePicker.find("minutes").getElement().value;

    		actual = hours +":"+minutes;
    		$A.test.assertEquals("11:23", actual, "The default value put in the inputText box, is not the value in the timePicker");
    	}
    },

    /**
     * Method allowing us to extract whether or not we are looking at a mobile device. Extracted from two functions because
     * depending on which mode we are in (Desktop or other), we either have a header with the Month Year combo or an outputText
     * and a select value
     *
     */
    isViewDesktop : function(){
    	return $A.get('$Browser').formFactor.toLowerCase() === "desktop";
    },

    /**
     * We have to ways that we need to get elements. Either from a output/select combo or from a header tag
     */
    getTextFromElm: function(cmp){
    	if(this.isViewDesktop()){
        	return $A.util.getText(cmp.find("calTitle").getElement());
        }

    	var year = cmp.find("yearTitle").getElement().value;
    	var month = $A.util.getText(cmp.find("monthTitle").getElement());

    	return month +" "+year;
    },

    openDatePicker : function(cmp) {
    	var opener = cmp.find("dateTimePickerTest").find("datePickerOpener").getElement();
    	var inputBox = cmp.find("dateTimePickerTest").find("inputText").getElement();
	var datePicker = cmp.find("dateTimePickerTest").find("datePicker").getElement();
	if($A.util.isUndefinedOrNull(opener)) {
            $A.test.clickOrTouch(inputBox);
	} else {
            $A.test.clickOrTouch(opener);
	}
	$A.test.addWaitFor(true, function(){return $A.util.hasClass(datePicker, "visible")});
    },

    getCleanDate : function(dateValue, hasTime) {
    	var dateSep = "-";
    	var timeSep = ":";
    	var someDate = dateValue ? new Date(dateValue) : new Date();
    	var retDate = (someDate.getMonth()+1) + dateSep +
    		someDate.getDate() + dateSep +
    		someDate.getFullYear();
    	if (hasTime) {
    		retDate += " " + someDate.getHours() + timeSep +
    			someDate.getMinutes();
    	}
    	return retDate;
    }
})<commit_msg>Re-enabling testSetLink and fixed it to work in AutoBuilds @rev ctatlah@ @bug W-2152983@<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 ({
    /**
      *  Test cancel link closes datePicker and does not perform any selection of date/time.
      */
    testCancelLink : {
    	attributes : {value: "2012-09-10 11:23", format: "MM-dd-yyyy hh:mm"},
    	test : [function(cmp) {
    		var input = cmp.find("dateTimePickerTest").find("inputText").getElement();
    		$A.test.assertNotNull(input, "input not visible");

    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		$A.test.assertEquals("2012-09-10 11:23", value, "Initial value incorrect");

    		this.openDatePicker(cmp);
    	}, function(cmp) {
    		var datePicker = cmp.find("dateTimePickerTest").find("datePicker");
    		var cancelLink = datePicker.find("cancel").getElement();

    		$A.test.clickOrTouch(cancelLink);
    		$A.test.addWaitFor(false, function(){return $A.util.hasClass(datePicker.getElement(), "visible")});

    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		$A.test.assertEquals("2012-09-10 11:23", value, "Cancel was pressed value should not have changed");
    	}]
    },

    /**
      *  Test set link sets the appropriate date/time.
      */
    testSetLink : {
    	attributes : {format: "MM/dd/yyyy hh:mm"},
    	test : [function(cmp) {

    		var input = cmp.find("dateTimePickerTest").find("inputText").getElement();
    		$A.test.assertNotNull(input, "input not visible");

    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		$A.test.assertEquals(undefined, value, "Initial value incorrect");

    		this.openDatePicker(cmp);
    	}, function(cmp) {

    		var datePicker = cmp.find("dateTimePickerTest").find("datePicker");
    		var setLink = datePicker.find("set").getElement();

    		$A.test.clickOrTouch(setLink);
    		$A.test.addWaitFor(false, function(){return $A.util.hasClass(datePicker.getElement(), "visible")});

    		var expectedDate = this.getCleanDate(null, true);
    		var value = cmp.find("dateTimePickerTest").get("v.value");
    		var setDate = cmp.find("dateTimePickerTest").find("inputText").getElement().value;

    		$A.test.assertEquals(expectedDate, setDate, "Incorrect datetime was set.");
    	}]
    },

    /**
     * Acessibility test, making sure that any functionality added is still accessible
     */
    testAccessibile : {
    	attributes : {value: "2012-09-10 11:23", format: "MM-dd-yyyy hh:mm"},
    	        test : [function(cmp) {
    	  			this.openDatePicker(cmp);
    	    	}, function(cmp) {
    	    		$A.test.assertAccessible();
    	}]
     },

    /**
      *  If value is set for date/time when opening up dateTimePicker it opens to the date of set value.
      */
    testCalendarWithTimeValuePreSet : {
    	attributes : {value: '09-10-2012T11:23Z', format: 'MM/dd/yyyy HH:mm', timezone: 'GMT'},
    	test : function(cmp) {
		this.openDatePicker(cmp);
    		var expected = "September 2012";
    		var datepicker = cmp.find("dateTimePickerTest").find("datePicker");
    		var actual = this.getTextFromElm(datepicker);

    		$A.test.assertEquals(expected, actual, "Month year of datePicker is not valid");
    		actual = $A.util.getText($A.test.getElementByClass("selectedDate")[0]);
    		$A.test.assertEquals("10", actual, "Day of month that is not correct");

    		//Grabbing timepicker values to make sure that everything is set correctly
    		var timePicker = datepicker.find("time");
    		var hours = timePicker.find("hours").getElement().value;
    		var minutes = timePicker.find("minutes").getElement().value;

    		actual = hours +":"+minutes;
    		$A.test.assertEquals("11:23", actual, "The default value put in the inputText box, is not the value in the timePicker");
    	}
    },

    /**
     * Method allowing us to extract whether or not we are looking at a mobile device. Extracted from two functions because
     * depending on which mode we are in (Desktop or other), we either have a header with the Month Year combo or an outputText
     * and a select value
     *
     */
    isViewDesktop : function(){
    	return $A.get('$Browser').formFactor.toLowerCase() === "desktop";
    },

    /**
     * We have to ways that we need to get elements. Either from a output/select combo or from a header tag
     */
    getTextFromElm: function(cmp){
    	if(this.isViewDesktop()){
        	return $A.util.getText(cmp.find("calTitle").getElement());
        }

    	var year = cmp.find("yearTitle").getElement().value;
    	var month = $A.util.getText(cmp.find("monthTitle").getElement());

    	return month +" "+year;
    },

    openDatePicker : function(cmp) {
    	var opener = cmp.find("dateTimePickerTest").find("datePickerOpener").getElement();
    	var inputBox = cmp.find("dateTimePickerTest").find("inputText").getElement();
	var datePicker = cmp.find("dateTimePickerTest").find("datePicker").getElement();
	if($A.util.isUndefinedOrNull(opener)) {
            $A.test.clickOrTouch(inputBox);
	} else {
            $A.test.clickOrTouch(opener);
	}
	$A.test.addWaitFor(true, function(){return $A.util.hasClass(datePicker, "visible")});
    },

    /*
     *  Checking for numbers that are less than 10, if it is adding in a 0 to the front
     */
    twoDigitFormat : function(num){
	num = "" + num;
	if(num.length < 2){
	    return "0" + num;
	}

	return "" + num;
    },

    getCleanDate : function(dateValue, hasTime) {
    	var dateSep = "/";
    	var timeSep = ":";
    	var someDate = dateValue ? new Date(dateValue) : new Date();
    	var retDate = this.twoDigitFormat(someDate.getMonth()+1) + dateSep +
    		this.twoDigitFormat(someDate.getDate()) + dateSep +
    		someDate.getFullYear();
    	if (hasTime) {
		retDate += " " + this.twoDigitFormat(someDate.getHours()%12) + timeSep + this.twoDigitFormat(someDate.getMinutes());
    	}
    	return retDate;
    }
})<|endoftext|>


<commit_before>'use strict';

const Promise = require('bluebird');

/*
 * Validate that at least one of the user fields have a value
 *
 * @param string userField
 *   The name of the field
 */
function isOneOfFieldSet() {
  // TODO: Move to module
  return ['user_id', 'email', 'mobile'].every(userField => !this[userField]);
}

/**
 * UserPassword
 *
 * @description :: Accepts and validates incoming POST request for user password.
 * @help        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

module.exports = {

  // Allow only whitelisted attributes.
  schema: true,

  // Turn off migrations.
  migrate: 'safe',

  // Turn off auto fields.
  autoCreatedAt: false,
  autoUpdatedAt: false,
  autoPK: false,

  // Validation rules.
  attributes: {
    user_id: {
      type: 'string',
      required: isOneOfFieldSet,
      hexadecimal: true,
      defaultsTo: '',
    },
    email: {
      type: 'string',
      required: isOneOfFieldSet,
      email: true,
      defaultsTo: '',
    },
    mobile: {
      type: 'string',
      required: isOneOfFieldSet,
      defaultsTo: '',
    },
    application_id: {
      type: 'string',
    },
    email_template: {
      type: 'string',
    },
    toMessage() {
      return Promise.join(
        NorthstarService.getUserFor(this),
        PhoenixService.User.getCount(),
        (user, count) => {
          const message = {
            activity: 'user_password',
            email: user.email,
            uid: user.drupalID,
            merge_vars: {
              MEMBER_COUNT: count.readable,
              FNAME: user.firstName,
              RESET_LINK: null,
            },
            user_country: user.country,
            user_language: user.language,
            email_template: null,
            email_tags: ['user_password'],
            activity_timestamp: null,
            application_id: null,
          };
          return message;
        }
      );
    },
  },

};
<commit_msg>Impliment NorthstarService.isOneOfFieldSet() in UserPassword field validation logic<commit_after>'use strict';

const Promise = require('bluebird');

/*
 * Validate that at least one of the user fields have a value
 *
 * @param string userField
 *   The name of the field
 */
function isOneOfFieldSet() {
  // TODO: Move to module
  return ['user_id', 'email', 'mobile'].every(userField => !this[userField]);
}

/**
 * UserPassword
 *
 * @description :: Accepts and validates incoming POST request for user password.
 * @help        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

module.exports = {

  // Allow only whitelisted attributes.
  schema: true,

  // Turn off migrations.
  migrate: 'safe',

  // Turn off auto fields.
  autoCreatedAt: false,
  autoUpdatedAt: false,
  autoPK: false,

  // Validation rules.
  attributes: {
    user_id: {
      type: 'string',
      required: NorthstarService.isOneOfFieldSet(this),
      hexadecimal: true,
      defaultsTo: '',
    },
    email: {
      type: 'string',
      required: NorthstarService.isOneOfFieldSet(this),
      email: true,
      defaultsTo: '',
    },
    mobile: {
      type: 'string',
      required: NorthstarService.isOneOfFieldSet(this),
      defaultsTo: '',
    },
    application_id: {
      type: 'string',
    },
    email_template: {
      type: 'string',
    },
    toMessage() {
      return Promise.join(
        NorthstarService.getUserFor(this),
        PhoenixService.User.getCount(),
        (user, count) => {
          const message = {
            activity: 'user_password',
            email: user.email,
            uid: user.drupalID,
            merge_vars: {
              MEMBER_COUNT: count.readable,
              FNAME: user.firstName,
              RESET_LINK: null,
            },
            user_country: user.country,
            user_language: user.language,
            email_template: null,
            email_tags: ['user_password'],
            activity_timestamp: null,
            application_id: null,
          };
          return message;
        }
      );
    },
  },

};
<|endoftext|>


<commit_before>(function() {

	switch (request.method) {
		case 'GET':
			res();
			return;

		case 'PUT':
			child_process.exec('./chinachu update', function(err, stdout, stderr) {
				if (err) return response.error(500);

				res();
			});
			return;
	}

	function res() {
		if (request.type === 'json') {

			var result = {
				time     : 0,
				conflicts: [],
				reserves : []
			};

			if (!fs.existsSync(define.SCHEDULER_LOG_FILE)) {
				response.head(204);
				response.end(JSON.stringify(result));
				return;
			}

			result.time = fs.statSync(define.SCHEDULER_LOG_FILE).mtime.getTime();

			var lines = fs.readFileSync(define.SCHEDULER_LOG_FILE, 'ascii').split('\n').reverse();

			for (var k = 0; k < lines.length; k++) {
				var line = lines[k] || '';

				if (line.match('RUNNING SCHEDULER.') !== null) {
					break;
				}

				if ((line.match('CONFLICT:') !== null) || (line.match('RESERVE:') !== null)) {
					var id = line.match(/(RESERVE|CONFLICT): ([a-z0-9-]+)/)[2];
					var t  = line.match(/(RESERVE|CONFLICT): ([a-z0-9-]+)/)[1];
					var f  = null;

					for (var i = 0; i < data.schedule.length; i++) {
						for (var j = 0; j < data.schedule[i].programs.length; j++) {
							if (data.schedule[i].programs[j].id === id) {
								f = data.schedule[i].programs[j];
								break;
							}
						}
						if (f !== null) { break; }
					}

					if (t === 'CONFLICT') {
						result.conflicts.push(f);
					}
					if (t === 'RESERVE') {
						result.reserves.push(f);
					}
				}
			}

			result.conflicts.reverse();
			result.reserves.reverse();

			response.head(200);
			response.end(JSON.stringify(result, null, '  '));

		} else {

			if (!fs.existsSync(define.SCHEDULER_LOG_FILE)) {
				response.head(204);
				response.end('');
				return;
			}

			response.head(200);
			response.end(fs.readFileSync(define.SCHEDULER_LOG_FILE, 'ascii'));

		}
	}

})();<commit_msg>api/script-scheduler.vm.js: scheduler ログファイルが大きすぎる場合にNodeが停止してしまうバグを修正<commit_after>(function() {

	switch (request.method) {
		case 'GET':
			res();
			return;

		case 'PUT':
			child_process.exec('./chinachu update', function(err, stdout, stderr) {
				if (err) return response.error(500);

				res();
			});
			return;
	}

	function res() {
		if (request.type === 'json') {

			var result = {
				time     : 0,
				conflicts: [],
				reserves : []
			};

			if (!fs.existsSync(define.SCHEDULER_LOG_FILE)) {
				response.head(204);
				response.end(JSON.stringify(result));
				return;
			}

			result.time = fs.statSync(define.SCHEDULER_LOG_FILE).mtime.getTime();

			var schedulerLog  = child_process.execSync('tail -n 256 "' + define.SCHEDULER_LOG_FILE + '"', {
				encoding: 'utf8'
			});

			var lines = schedulerLog.split('\n').reverse();

			for (var k = 0; k < lines.length; k++) {
				var line = lines[k] || '';

				if (line.match('RUNNING SCHEDULER.') !== null) {
					break;
				}

				if ((line.match('CONFLICT:') !== null) || (line.match('RESERVE:') !== null)) {
					var id = line.match(/(RESERVE|CONFLICT): ([a-z0-9-]+)/)[2];
					var t  = line.match(/(RESERVE|CONFLICT): ([a-z0-9-]+)/)[1];
					var f  = null;

					for (var i = 0; i < data.schedule.length; i++) {
						for (var j = 0; j < data.schedule[i].programs.length; j++) {
							if (data.schedule[i].programs[j].id === id) {
								f = data.schedule[i].programs[j];
								break;
							}
						}
						if (f !== null) { break; }
					}

					if (t === 'CONFLICT') {
						result.conflicts.push(f);
					}
					if (t === 'RESERVE') {
						result.reserves.push(f);
					}
				}
			}

			result.conflicts.reverse();
			result.reserves.reverse();

			response.head(200);
			response.end(JSON.stringify(result, null, '  '));

		} else {

			if (!fs.existsSync(define.SCHEDULER_LOG_FILE)) {
				response.head(204);
				response.end('');
				return;
			}

			response.head(200);
			response.end(fs.readFileSync(define.SCHEDULER_LOG_FILE, 'ascii'));

		}
	}

})();<|endoftext|>


<commit_before>
angular.module("App", []);
angular
	.module("App")
		.controller("dropController", function($scope) {

			$scope.aberto = true;

			$scope.logChange = function( $event ) {
				$event.preventDefault()
				$scope.aberto = !$scope.aberto;
			};

		})
		.controller("menuController", function($scope) {
			$scope.aberto = false;

			$scope.menus = ["paginas","log","usuarios"];

			$scope.clickMenu = function( $event ){
				$event.preventDefault()
				$scope.aberto = !$scope.aberto;
			}
		});<commit_msg>Adição de dependência<commit_after>
angular.module("App", ['ui.calendar']);
angular
	.module("App")
		.controller("dropController", function($scope) {

			$scope.aberto = true;

			$scope.logChange = function( $event ) {
				$event.preventDefault()
				$scope.aberto = !$scope.aberto;
			};

		})
		.controller("menuController", function($scope) {
			$scope.aberto = false;

			$scope.menus = ["paginas","log","usuarios"];

			$scope.clickMenu = function( $event ){
				$event.preventDefault()
				$scope.aberto = !$scope.aberto;
			}
		});<|endoftext|>


<commit_before>define(
  'ephox.alloy.behaviour.common.BehaviourBlob',

  [
    'ephox.alloy.behaviour.common.NoState',
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.katamari.api.Arr',
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Obj',
    'ephox.sand.api.JSON',
    'global!Error'
  ],

  function (NoState, FieldPresence, FieldSchema, ValueSchema, Arr, Fun, Obj, JSON, Error) {
    var generateFrom = function (spec, all) {
      var schema = Arr.map(all, function (a) {
        return FieldSchema.field(a.name(), a.name(), FieldPresence.asOption(), ValueSchema.objOf([
          FieldSchema.strict('config'),
          FieldSchema.defaulted('state', NoState)
        ]));
      });

      var data = ValueSchema.asStruct('component.behaviours', ValueSchema.objOf(schema), spec.behaviours).fold(function (errInfo) {
        throw new Error(
          ValueSchema.formatError(errInfo) + '\nComplete spec:\n' +
            JSON.stringify(spec, null, 2)
        );
      }, Fun.identity);

      return {
        list: all,
        data: Obj.map(data, function (v, k) {
          return Fun.constant(v().map(function (vv) {
            return {
              config: vv.config(),
              state: vv.state().init(vv.config())
            };
          }));
        })
      };
    };

    var getBehaviours = function (bData) {
      return bData.list;
    };

    var getData = function (bData) {
      return bData.data;
    };

    return {
      generateFrom: generateFrom,
      getBehaviours: getBehaviours,
      getData: getData
    };
  }
);
<commit_msg>VAN-81: slight variable renames<commit_after>define(
  'ephox.alloy.behaviour.common.BehaviourBlob',

  [
    'ephox.alloy.behaviour.common.NoState',
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.katamari.api.Arr',
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Obj',
    'ephox.sand.api.JSON',
    'global!Error'
  ],

  function (NoState, FieldPresence, FieldSchema, ValueSchema, Arr, Fun, Obj, JSON, Error) {
    var generateFrom = function (spec, all) {
      var schema = Arr.map(all, function (a) {
        return FieldSchema.field(a.name(), a.name(), FieldPresence.asOption(), ValueSchema.objOf([
          FieldSchema.strict('config'),
          FieldSchema.defaulted('state', NoState)
        ]));
      });

      var validated = ValueSchema.asStruct('component.behaviours', ValueSchema.objOf(schema), spec.behaviours).fold(function (errInfo) {
        throw new Error(
          ValueSchema.formatError(errInfo) + '\nComplete spec:\n' +
            JSON.stringify(spec, null, 2)
        );
      }, Fun.identity);

      return {
        list: all,
        data: Obj.map(validated, function (blobOptionThunk/*, rawK */) {
          var blobOption = blobOptionThunk();
          return Fun.constant(blobOption.map(function (blob) {
            return {
              config: blob.config(),
              state: blob.state().init(blob.config())
            };
          }));
        })
      };
    };

    var getBehaviours = function (bData) {
      return bData.list;
    };

    var getData = function (bData) {
      return bData.data;
    };

    return {
      generateFrom: generateFrom,
      getBehaviours: getBehaviours,
      getData: getData
    };
  }
);
<|endoftext|>


<commit_before>module.exports = (function () { // eslint-disable-line no-unused-vars
  function isUndefined (suspect) {
    return suspect === undefined; // eslint-disable-line no-undefined
  }

  function requireArgument (value, message) {
    if (isUndefined(value)) { throw new Error(message); }
  }

  function SpecialCoverageLoader (element, listElement, options) {
    requireArgument(element, 'new SpecialCoverageLoader(element, listElement, options): element is undefined');
    requireArgument(listElement, 'new SpecialCoverageLoader(element, listElement, options): listElement is undefined');
    requireArgument(element.dataset.total, 'new SpecialCoverageLoader(element, listElement, options): element has no data-total value');
    requireArgument(element.dataset.perPage, 'new SpecialCoverageLoader(element, listElement, options): element has no data-per-page value');

    options = options || {};
    this.total = parseInt(element.dataset.total, 10);
    this.perPage = parseInt(element.dataset.perPage, 10);
    this.currentPage = 1;
    this.listElement = listElement;
    this.element = element;
    this.isLoading = false;
    this.defaultText = element.innerHTML;
    this.loadingText = 'Loading...';

    options = Object.assign({
      baseUrl: window.location.href,
    }, options);

    Object.keys(options).forEach(function (key) {
      this[key] = options[key];
    }.bind(this));

    element.addEventListener('click', function () {
      var url = this.buildUrl(this.currentPage, this.perPage, this.baseUrl);
      this.loadMore(url);
    }.bind(this));
  }

  Object.assign(SpecialCoverageLoader.prototype, {
    nextOffset: function (currentPage, perPage) {
      requireArgument(currentPage, 'SpecialCoverageLoader.nextOffset(currentPage, perPage): currentPage is undefined');
      requireArgument(perPage, 'SpecialCoverageLoader.nextOffset(currentPage, perPage): perPage is undefined');

      return currentPage * perPage;
    },

    buildUrl: function (currentPage, perPage, baseUrl) {
      requireArgument(currentPage, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): currentPage is undefined');
      requireArgument(perPage, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): perPage is undefined');
      requireArgument(baseUrl, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): baseUrl is undefined');

      var offset = this.nextOffset(currentPage, perPage);

      return [baseUrl, 'more', offset].join('/');
    },

    loadMore: function (url) {
      if (this.isLoading) { return; }
      requireArgument(url, 'SpecialCoverageLoader.loadMore(url): url is undefined');
      this.isLoading = true;
      this.element.innerHTML = this.loadingText;
      $.ajax({
        url: url,
        type: 'get',
        dataType: 'html',
      })
        .done(this.handleLoadMoreSuccess.bind(this))
        .fail(this.handleLoadMoreFailure.bind(this));
    },

    toggleLoadingState: function (loadingState, element) {
      requireArgument(loadingState, 'SpecialCoverageLoader.toggleLoadingState(loadingState, element): loadingState is undefined');
      requireArgument(element, 'SpecialCoverageLoader.toggleLoadingState(loadingState, element): element is undefined');
      this.isLoading = !loadingState;
      element.innerHTML = this.isLoading ? this.loadingText : this.defaultText;
    },

    handleLoadMoreSuccess: function (response) {
      this.toggleLoadingState(this.isLoading, this.element);
      requireArgument(response, 'SpecialCoverageLoader.handleLoadMoreSuccess(response): response is undefined');
      response = response.trim();
      if (response) {
        this.currentPage += 1;
        this.listElement.innerHTML = this.listElement.innerHTML + response;
      }
      this.setButtonVisibility(response);
    },

    handleLoadMoreFailure: function (response) {
      this.toggleLoadingState(this.isLoading, this.element);
      requireArgument(response, 'SpecialCoverageLoader.handleLoadMoreFailure(response): response id undefined');

      var message = [
        'SpecialCoverageLoader.loadMore("',
        this.buildUrl(this.currentPage, this.perPage, this.baseUrl),
        '"): server responded with "',
        response.status,
        ' ',
        response.statusText,
        '"',
      ].join('');

      console.log(message);
    },

    hideElement: function () {
      this.element.style.display = 'none';
    },

    isLastPage: function (total, listElement) {
      requireArgument(total, 'SpecialCoverageLoader.isLastPage(total, listElement): total is undefined');
      requireArgument(listElement, 'SpecialCoverageLoader.isLastPage(total, listElement): listElement is undefined');

      return total === listElement.children.length;
    },

    setButtonVisibility: function (response) {
      requireArgument(response, 'SpecialCoverageLoader.setButtonVisibility(response): response is undefined');

      if (!response || this.isLastPage(this.total, this.listElement)) {
        this.hideElement();
      }
    },
  });
  return SpecialCoverageLoader;
})();
<commit_msg>No loop necessary<commit_after>module.exports = (function () { // eslint-disable-line no-unused-vars
  function isUndefined (suspect) {
    return suspect === undefined; // eslint-disable-line no-undefined
  }

  function requireArgument (value, message) {
    if (isUndefined(value)) { throw new Error(message); }
  }

  function SpecialCoverageLoader (element, listElement, options) {
    requireArgument(element, 'new SpecialCoverageLoader(element, listElement, options): element is undefined');
    requireArgument(listElement, 'new SpecialCoverageLoader(element, listElement, options): listElement is undefined');
    requireArgument(element.dataset.total, 'new SpecialCoverageLoader(element, listElement, options): element has no data-total value');
    requireArgument(element.dataset.perPage, 'new SpecialCoverageLoader(element, listElement, options): element has no data-per-page value');

    options = options || {};
    this.total = parseInt(element.dataset.total, 10);
    this.perPage = parseInt(element.dataset.perPage, 10);
    this.currentPage = 1;
    this.listElement = listElement;
    this.element = element;
    this.isLoading = false;
    this.defaultText = element.innerHTML;
    this.loadingText = 'Loading...';

    options = Object.assign({
      baseUrl: window.location.href,
    }, options);

    Object.assign(this, options);

    element.addEventListener('click', function () {
      var url = this.buildUrl(this.currentPage, this.perPage, this.baseUrl);
      this.loadMore(url);
    }.bind(this));
  }

  Object.assign(SpecialCoverageLoader.prototype, {
    nextOffset: function (currentPage, perPage) {
      requireArgument(currentPage, 'SpecialCoverageLoader.nextOffset(currentPage, perPage): currentPage is undefined');
      requireArgument(perPage, 'SpecialCoverageLoader.nextOffset(currentPage, perPage): perPage is undefined');

      return currentPage * perPage;
    },

    buildUrl: function (currentPage, perPage, baseUrl) {
      requireArgument(currentPage, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): currentPage is undefined');
      requireArgument(perPage, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): perPage is undefined');
      requireArgument(baseUrl, 'SpecialCoverageLoader.buildUrl(currentPage, perPage, baseUrl, offset): baseUrl is undefined');

      var offset = this.nextOffset(currentPage, perPage);

      return [baseUrl, 'more', offset].join('/');
    },

    loadMore: function (url) {
      if (this.isLoading) { return; }
      requireArgument(url, 'SpecialCoverageLoader.loadMore(url): url is undefined');
      this.isLoading = true;
      this.element.innerHTML = this.loadingText;
      $.ajax({
        url: url,
        type: 'get',
        dataType: 'html',
      })
        .done(this.handleLoadMoreSuccess.bind(this))
        .fail(this.handleLoadMoreFailure.bind(this));
    },

    toggleLoadingState: function (loadingState, element) {
      requireArgument(loadingState, 'SpecialCoverageLoader.toggleLoadingState(loadingState, element): loadingState is undefined');
      requireArgument(element, 'SpecialCoverageLoader.toggleLoadingState(loadingState, element): element is undefined');
      this.isLoading = !loadingState;
      element.innerHTML = this.isLoading ? this.loadingText : this.defaultText;
    },

    handleLoadMoreSuccess: function (response) {
      this.toggleLoadingState(this.isLoading, this.element);
      requireArgument(response, 'SpecialCoverageLoader.handleLoadMoreSuccess(response): response is undefined');
      response = response.trim();
      if (response) {
        this.currentPage += 1;
        this.listElement.innerHTML = this.listElement.innerHTML + response;
      }
      this.setButtonVisibility(response);
    },

    handleLoadMoreFailure: function (response) {
      this.toggleLoadingState(this.isLoading, this.element);
      requireArgument(response, 'SpecialCoverageLoader.handleLoadMoreFailure(response): response id undefined');

      var message = [
        'SpecialCoverageLoader.loadMore("',
        this.buildUrl(this.currentPage, this.perPage, this.baseUrl),
        '"): server responded with "',
        response.status,
        ' ',
        response.statusText,
        '"',
      ].join('');

      console.log(message);
    },

    hideElement: function () {
      this.element.style.display = 'none';
    },

    isLastPage: function (total, listElement) {
      requireArgument(total, 'SpecialCoverageLoader.isLastPage(total, listElement): total is undefined');
      requireArgument(listElement, 'SpecialCoverageLoader.isLastPage(total, listElement): listElement is undefined');

      return total === listElement.children.length;
    },

    setButtonVisibility: function (response) {
      requireArgument(response, 'SpecialCoverageLoader.setButtonVisibility(response): response is undefined');

      if (!response || this.isLastPage(this.total, this.listElement)) {
        this.hideElement();
      }
    },
  });
  return SpecialCoverageLoader;
})();
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { Button, Card, CardBlock, CardTitle, CardSubtitle, Col, Input, Form, FormGroup, Label } from 'reactstrap'
import Autosuggest from 'react-autosuggest'
import ConfirmRejectModal from '../ConfirmRejectModal/ConfirmRejectModal'
import EditBar from '../EditBar/EditBar'
import ChipInput from 'material-ui-chip-input'

import styles from './Edit.css'
import autosuggest from './autosuggest.css'

class Edit extends Component {
  static propTypes = {
    dataDir: PropTypes.string.isRequired,
    editedProduct: PropTypes.object.isRequired,
    orderedKeys: PropTypes.array.isRequired,
    products: PropTypes.array.isRequired,
    actions: PropTypes.object.isRequired
  }

  state = {
    saveModalOpen: false,
    backModalOpen: false,
    suggestions: [], // for autosuggest
    value: '' // for autosuggest
  }

  // Teach Autosuggest how to calculate suggestions for any given input value.
  getSuggestions = value => {
    const inputValue = value.trim().toLowerCase()
    const inputLength = inputValue.length

    return inputLength === 0 ? [] : this.props.products.filter(product =>
      product.name !== null && product.name !== undefined && product.name.toLowerCase().slice(0, inputLength) === inputValue
    )
  }

  getSuggestionValue = suggestion => suggestion.id.toString()

  // Autosuggest will call this function every time you need to update
  // suggestions
  handleSuggestionFetch = ({ value }) => {
    this.setState({
      suggestions: this.getSuggestions(value)
    })
  }

  // Autosuggest will call this function every time you need to clear suggestions.
  handleSuggestionClear = () => {
    this.setState({
      suggestions: []
    })
  }

  toggleSaveModal = () => {
    this.setState({
      saveModalOpen: !this.state.saveModalOpen
    })
  }

  // Use your imagination to render suggestions.
  renderSuggestion = suggestion => (

      {`${suggestion.name} (id: ${suggestion.id})`}

  )

  toggleBackModal = () => {
    this.setState({
      backModalOpen: !this.state.backModalOpen
    })
  }

  togglePopover = () => {
    this.setState({
      popoverOpen: !this.state.popoverOpen
    })
  }

  handleSaveConfirmClick = () => {
    this.props.actions.mergeEditedToProducts()
    this.props.actions.saveAllProducts()
    this.toggleSaveModal()
  }

  handleBackConfirmClick = () => {
    this.props.actions.clearSearchInput()
    this.props.actions.changeLocation('/')
    this.toggleBackModal()
  }

  handleInputChange = event => {
    this.props.actions.updateEditedProduct(event.target.id, event.target.value)
  }

  handleAutosuggestInputChange = (event, { newValue }) => {
    this.setState({
      value: newValue
    })
  }

  handleSynonymChange = synonyms => {
    this.props.actions.updateEditedProduct('synonyms', synonyms)
  }

  renderFormGroup = () => {
    return this.props.orderedKeys.map(key => {
      const renderInputs = () => {
        switch (key) {
          case 'filename':
            return

          case 'validationSummary':
            return

          case 'id':
            // id is read only!
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    readOnly
                    value={this.props.editedProduct[key]} />
                </Col>

            )

          case 'processes':
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    readOnly
                    value='Processes array not editable... Sorry!' />
                </Col>

            )

          case 'linked-id':
            // Autosuggest will pass through all these props to the input
            // element
            const inputProps = {
              placeholder: 'Search for product name...',
              value: this.state.value,
              onChange: this.handleAutosuggestInputChange
            }
            return (

                  {key}

                <Col sm={8}>
                  <Autosuggest
                    id={key}
                    theme={autosuggest}
                    suggestions={this.state.suggestions}
                    inputProps={inputProps}
                    onSuggestionsFetchRequested={this.handleSuggestionFetch}
                    onSuggestionsClearRequested={this.handleSuggestionClear}
                    getSuggestionValue={this.getSuggestionValue}
                    renderSuggestion={this.renderSuggestion} />
                </Col>

            )

          case 'synonyms':
            return (

                  {key}

                <Col sm={8}>
                  <ChipInput
                    defaultValue={this.props.editedProduct.synonyms}
                    onChange={(synonyms) => this.handleSynonymChange(synonyms)}
                    fullWidthInput
                    style={{ width: '100%' }}
                  />
                </Col>

            )

          default:
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    onChange={this.handleInputChange}
                    value={this.props.editedProduct[key] || ''} />
                </Col>

            )
        }
      }

      return (
        <FormGroup key={key} row>
          {renderInputs()}
        </FormGroup>
      )
    })
  }

  renderEditView = () => {
    return (

        <Card>
          <CardBlock>
            <CardTitle>{this.props.editedProduct.name}</CardTitle>
            <CardSubtitle>{this.props.editedProduct.filename}</CardSubtitle>
          </CardBlock>
          <CardBlock>
            <Form>
              {this.renderFormGroup()}
            </Form>
          </CardBlock>
          <CardBlock>

              <Col sm={3}>
                <Button
                  onClick={() => this.toggleSaveModal()}
                  outline
                  color='success'>
                  Save changes
                </Button>
                <ConfirmRejectModal
                  isOpen={this.state.saveModalOpen}
                  toggle={this.toggleSaveModal}
                  onConfirmClick={this.handleSaveConfirmClick}
                  onRejectClick={this.toggleSaveModal}
                  header='Saving will overwrite file!'
                  body={`Clicking save will overwrite ${this.props.editedProduct.filename}! Are you sure?`}
                  confirmBtnText='Save!'
                  rejectBtnText='Cancel'
                  />
              </Col>

          </CardBlock>
        </Card>

    )
  }

  render () {
    return (

        <EditBar
          actions={this.props.actions}
          filename={this.props.editedProduct.filename}
          saveModalOpen={this.state.saveModalOpen}
          backModalOpen={this.state.backModalOpen}
          toggleSaveModal={this.toggleSaveModal}
          toggleBackModal={this.toggleBackModal}
          handleSaveConfirmClick={this.handleSaveConfirmClick}
          handleBackConfirmClick={this.handleBackConfirmClick}
          handleSaveRejectClick={this.toggleSaveModal}
          handleBackRejectClick={this.toggleBackModal} />
        {this.renderEditView()}

    )
  }
}

export default Edit
<commit_msg>Autosuggest values now change edited product and get saved to prods.all.json<commit_after>import React, { Component, PropTypes } from 'react'
import { Button, Card, CardBlock, CardTitle, CardSubtitle, Col, Input, Form, FormGroup, Label } from 'reactstrap'
import Autosuggest from 'react-autosuggest'
import ConfirmRejectModal from '../ConfirmRejectModal/ConfirmRejectModal'
import EditBar from '../EditBar/EditBar'
import ChipInput from 'material-ui-chip-input'

import styles from './Edit.css'
import autosuggest from './autosuggest.css'

class Edit extends Component {
  static propTypes = {
    dataDir: PropTypes.string.isRequired,
    editedProduct: PropTypes.object.isRequired,
    orderedKeys: PropTypes.array.isRequired,
    products: PropTypes.array.isRequired,
    actions: PropTypes.object.isRequired
  }

  state = {
    saveModalOpen: false,
    backModalOpen: false,
    suggestions: [], // for autosuggest
    autosuggestId: '',
    autosuggestValue: ''
  }

  // Teach Autosuggest how to calculate suggestions for any given input value.
  getSuggestions = value => {
    const inputValue = value.trim().toLowerCase()
    const inputLength = inputValue.length

    return inputLength === 0 ? [] : this.props.products.filter(product =>
      product.name !== null && product.name !== undefined && product.name.toLowerCase().slice(0, inputLength) === inputValue
    )
  }

  getSuggestionValue = suggestion => suggestion.id.toString()

  // Autosuggest will call this function every time you need to update
  // suggestions
  handleSuggestionFetch = ({ value }) => {
    this.setState({
      suggestions: this.getSuggestions(value)
    })
  }

  // Autosuggest will call this function every time you need to clear suggestions.
  handleSuggestionClear = () => {
    this.setState({
      suggestions: []
    })
  }

  toggleSaveModal = () => {
    this.setState({
      saveModalOpen: !this.state.saveModalOpen
    })
  }

  // Use your imagination to render suggestions.
  renderSuggestion = suggestion => (

      {`${suggestion.name} (id: ${suggestion.id})`}

  )

  toggleBackModal = () => {
    this.setState({
      backModalOpen: !this.state.backModalOpen
    })
  }

  togglePopover = () => {
    this.setState({
      popoverOpen: !this.state.popoverOpen
    })
  }

  handleSaveConfirmClick = () => {
    this.props.actions.mergeEditedToProducts()
    this.props.actions.saveAllProducts()
    this.toggleSaveModal()
  }

  handleBackConfirmClick = () => {
    this.props.actions.clearSearchInput()
    this.props.actions.changeLocation('/')
    this.toggleBackModal()
  }

  handleInputChange = (event, { newValue }) => {
    // HACK: How to get the id when autosuggest is clicked??? Here I get it
    // from previous input into the search field and "cache" it...
    if (event.target.id) {
      this.setState({
        autosuggestId: event.target.id
      })
    }

    this.setState({
      autosuggestValue: newValue
    })
    this.props.actions.updateEditedProduct(this.state.autosuggestId, newValue)
  }

  handleSynonymChange = synonyms => {
    this.props.actions.updateEditedProduct('synonyms', synonyms)
  }

  renderFormGroup = () => {
    return this.props.orderedKeys.map(key => {
      const renderInputs = () => {
        switch (key) {
          case 'filename':
            return

          case 'validationSummary':
            return

          case 'id':
            // id is read only!
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    readOnly
                    value={this.props.editedProduct[key]} />
                </Col>

            )

          case 'processes':
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    readOnly
                    value='Processes array not editable... Sorry!' />
                </Col>

            )

          case 'linked-id':
            // Autosuggest will pass through all these props to the input
            // element
            const inputProps = {
              id: 'linked-id',
              placeholder: 'Search for product name...',
              value: this.props.editedProduct[key] ||
                this.state.autosuggestValue,
              onChange: this.handleInputChange
            }
            return (

                  {key}

                <Col sm={8}>
                  <Autosuggest
                    id={key}
                    theme={autosuggest}
                    suggestions={this.state.suggestions}
                    inputProps={inputProps}
                    onSuggestionsFetchRequested={this.handleSuggestionFetch}
                    onSuggestionsClearRequested={this.handleSuggestionClear}
                    getSuggestionValue={this.getSuggestionValue}
                    renderSuggestion={this.renderSuggestion} />
                </Col>

            )

          case 'synonyms':
            return (

                  {key}

                <Col sm={8}>
                  <ChipInput
                    defaultValue={this.props.editedProduct.synonyms}
                    onChange={(synonyms) => this.handleSynonymChange(synonyms)}
                    fullWidthInput
                    style={{ width: '100%' }}
                  />
                </Col>

            )

          default:
            return (

                  {key}

                <Col sm={8}>
                  <Input
                    type='text'
                    id={key}
                    onChange={this.handleInputChange}
                    value={this.props.editedProduct[key] || ''} />
                </Col>

            )
        }
      }

      return (
        <FormGroup key={key} row>
          {renderInputs()}
        </FormGroup>
      )
    })
  }

  renderEditView = () => {
    return (

        <Card>
          <CardBlock>
            <CardTitle>{this.props.editedProduct.name}</CardTitle>
            <CardSubtitle>{this.props.editedProduct.filename}</CardSubtitle>
          </CardBlock>
          <CardBlock>
            <Form>
              {this.renderFormGroup()}
            </Form>
          </CardBlock>
          <CardBlock>

              <Col sm={3}>
                <Button
                  onClick={() => this.toggleSaveModal()}
                  outline
                  color='success'>
                  Save changes
                </Button>
                <ConfirmRejectModal
                  isOpen={this.state.saveModalOpen}
                  toggle={this.toggleSaveModal}
                  onConfirmClick={this.handleSaveConfirmClick}
                  onRejectClick={this.toggleSaveModal}
                  header='Saving will overwrite file!'
                  body={`Clicking save will overwrite ${this.props.editedProduct.filename}! Are you sure?`}
                  confirmBtnText='Save!'
                  rejectBtnText='Cancel'
                  />
              </Col>

          </CardBlock>
        </Card>

    )
  }

  render () {
    return (

        <EditBar
          actions={this.props.actions}
          filename={this.props.editedProduct.filename}
          saveModalOpen={this.state.saveModalOpen}
          backModalOpen={this.state.backModalOpen}
          toggleSaveModal={this.toggleSaveModal}
          toggleBackModal={this.toggleBackModal}
          handleSaveConfirmClick={this.handleSaveConfirmClick}
          handleBackConfirmClick={this.handleBackConfirmClick}
          handleSaveRejectClick={this.toggleSaveModal}
          handleBackRejectClick={this.toggleBackModal} />
        {this.renderEditView()}

    )
  }
}

export default Edit
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { setKeys } from '../modules/account';
import Delete from 'react-icons/lib/md/delete';
import _ from 'lodash';
import storage from 'electron-json-storage';
import * as Neon from 'neon-js'
import { initiateGetBalance, intervals, NetworkSwitch } from "../components/NetworkSwitch";
import { sendEvent, clearTransactionEvent } from '../modules/transactions';
import { updateRpxBalance } from '../modules/rpx';
import Buffer from 'Buffer'

const logo = require('../images/neon-logo2.png');

let scriptHashElement, neoToSend;

const refreshTokenBalance = (dispatch, net, address, silent = false) => {
  // TODO: add other check
  if (scriptHashElement.value.length !== 40){
    if (!silent){
      dispatch(sendEvent(false, "Not a valid script hash."));
      setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    }
    return false;
  }
  Neon.getTokenBalance(net, scriptHashElement.value, address).then((balance) => {
    console.log(balance)
    dispatch(updateRpxBalance(balance))
  }).catch((e) => {
    dispatch(updateRpxBalance(0))
    dispatch(sendEvent(false, "There is no ability to display tokens at that script hash."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  });
}

const participateInSale = (dispatch, net, wif, totalNeo) => {
  const account = Neon.getAccountFromWIFKey(wif);
  if (parseFloat(neoToSend.value) !== parseInt(neoToSend.value)){
    dispatch(sendEvent(false, "You cannot send fractional Neo to a token sale."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  }
  if (parseInt(neoToSend.value) > totalNeo){
    dispatch(sendEvent(false, "You do not have enough Neo to send."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  }
  Neon.getTokenBalance(net, scriptHashElement.value, account.address).then((balance) => {
    if(balance > 0){
      // already have tokens, do not participate in sale
      dispatch(sendEvent(false, "This address already has tokens, preventing participation."));
      setTimeout(() => dispatch(clearTransactionEvent()), 5000);
      return false;
    }
    else{
      Neon.doMintTokens(net, wif, parseInt(neoToSend.value), 0).then((response) => {
        if(response.result === true){
          dispatch(sendEvent(true, "Sale participation was successful."));
          setTimeout(() => dispatch(clearTransactionEvent()), 5000);
          return true;
        }
        else{
          dispatch(sendEvent(false, "Sale participation failed."));
          setTimeout(() => dispatch(clearTransactionEvent()), 5000);
          return false;
        }
      })
    }
  }).catch((e) => {
    dispatch(sendEvent(false, "This script hash cannot mint tokens."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  });
};

const saveSettings = (settings) => {
  storage.set('settings', settings);
};

class TokenSale extends Component {

  componentDidUpdate = () => {
    initiateGetBalance(this.props.dispatch, this.props.net, this.props.address)
    refreshTokenBalance(this.props.dispatch, this.props.net, this.props.address, true)
  }

  render = () =>

      <NetworkSwitch />

Participate in Token Sale

NEO Balance:

{this.props.neo}

Token Balance:

{this.props.rpx}

Script Hash

          <input type="text" className="scriptHash" ref={(node) => scriptHashElement = node}></input>

Amount of NEO to Send:

            <input type="text" className="neoAmount" placeholder="e.g., 100" ref={(node) => neoToSend = node}/>

          <button onClick={() => participateInSale(this.props.dispatch, this.props.net, this.props.wif, this.props.neo)}>Submit for Sale</button>
          <button onClick={() => refreshTokenBalance(this.props.dispatch, this.props.net, this.props.address)}>Refresh Token Balance</button>

      <Link to="/"><button className="altButton">Home</button></Link>

;
}

const mapStateToProps = (state) => ({
  explorer: state.metadata.blockExplorer,
  wif: state.account.wif,
  neo: state.wallet.Neo,
  net: state.metadata.network,
  address: state.account.address,
  wallets: state.account.accountKeys,
  rpx: state.rpx.RPX
});

TokenSale = connect(mapStateToProps)(TokenSale);

export default TokenSale;
<commit_msg>remove limit<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { setKeys } from '../modules/account';
import Delete from 'react-icons/lib/md/delete';
import _ from 'lodash';
import storage from 'electron-json-storage';
import * as Neon from 'neon-js'
import { initiateGetBalance, intervals, NetworkSwitch } from "../components/NetworkSwitch";
import { sendEvent, clearTransactionEvent } from '../modules/transactions';
import { updateRpxBalance } from '../modules/rpx';
import Buffer from 'Buffer'

const logo = require('../images/neon-logo2.png');

let scriptHashElement, neoToSend;

const refreshTokenBalance = (dispatch, net, address, silent = false) => {
  // TODO: add other check
  if (scriptHashElement.value.length !== 40){
    if (!silent){
      dispatch(sendEvent(false, "Not a valid script hash."));
      setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    }
    return false;
  }
  Neon.getTokenBalance(net, scriptHashElement.value, address).then((balance) => {
    console.log(balance)
    dispatch(updateRpxBalance(balance))
  }).catch((e) => {
    dispatch(updateRpxBalance(0))
    dispatch(sendEvent(false, "There is no ability to display tokens at that script hash."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  });
}

const participateInSale = (dispatch, net, wif, totalNeo) => {
  const account = Neon.getAccountFromWIFKey(wif);
  if (parseFloat(neoToSend.value) !== parseInt(neoToSend.value)){
    dispatch(sendEvent(false, "You cannot send fractional Neo to a token sale."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  }
  if (parseInt(neoToSend.value) > totalNeo){
    dispatch(sendEvent(false, "You do not have enough Neo to send."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  }
  Neon.getTokenBalance(net, scriptHashElement.value, account.address).then((balance) => {
      Neon.doMintTokens(net, wif, parseInt(neoToSend.value), 0).then((response) => {
        if(response.result === true){
          dispatch(sendEvent(true, "Sale participation was successful."));
          setTimeout(() => dispatch(clearTransactionEvent()), 5000);
          return true;
        }
        else{
          dispatch(sendEvent(false, "Sale participation failed."));
          setTimeout(() => dispatch(clearTransactionEvent()), 5000);
          return false;
        }
      })
  }).catch((e) => {
    dispatch(sendEvent(false, "This script hash cannot mint tokens."));
    setTimeout(() => dispatch(clearTransactionEvent()), 5000);
    return false;
  });
};

const saveSettings = (settings) => {
  storage.set('settings', settings);
};

class TokenSale extends Component {

  componentDidUpdate = () => {
    initiateGetBalance(this.props.dispatch, this.props.net, this.props.address)
    refreshTokenBalance(this.props.dispatch, this.props.net, this.props.address, true)
  }

  render = () =>

      <NetworkSwitch />

Participate in Token Sale

NEO Balance:

{this.props.neo}

Token Balance:

{this.props.rpx}

Script Hash

          <input type="text" className="scriptHash" ref={(node) => scriptHashElement = node}></input>

Amount of NEO to Send:

            <input type="text" className="neoAmount" placeholder="e.g., 100" ref={(node) => neoToSend = node}/>

          <button onClick={() => participateInSale(this.props.dispatch, this.props.net, this.props.wif, this.props.neo)}>Submit for Sale</button>
          <button onClick={() => refreshTokenBalance(this.props.dispatch, this.props.net, this.props.address)}>Refresh Token Balance</button>

      <Link to="/"><button className="altButton">Home</button></Link>

;
}

const mapStateToProps = (state) => ({
  explorer: state.metadata.blockExplorer,
  wif: state.account.wif,
  neo: state.wallet.Neo,
  net: state.metadata.network,
  address: state.account.address,
  wallets: state.account.accountKeys,
  rpx: state.rpx.RPX
});

TokenSale = connect(mapStateToProps)(TokenSale);

export default TokenSale;
<|endoftext|>


<commit_before>import Ember from 'ember';
import triggerAnalytics from 'irene/utils/trigger-analytics';

const {inject: {service}} = Ember;

export default Ember.Component.extend({

  session: service(),

  isLoaded: false,
  isSecurityEnabled: false,
  isSecurityDashboard: false,

  org: (function() {
    return this.get('store').queryRecord('organization', {id: this.get('organization.id')})
  }).property(),

  securityEnabled() {
    this.get("ajax").request("projects", {namespace: 'hudson-api'})
    .then(() => {
      this.set("isSecurityEnabled", true);
      this.securityDashboard();
    }, () => {
      this.set("isSecurityEnabled", false);
      this.securityDashboard();
    });
  },

  securityDashboard() {
    if(window.location.pathname.startsWith("/security")) {
      const isSecurityEnabled = this.get("isSecurityEnabled");
      if(isSecurityEnabled) {
        this.set("isSecurityDashboard", true);
      }
      else {
        Ember.getOwner(this).lookup('route:authenticated').transitionTo("authenticated.projects");
      }
      this.set("isLoaded", true);
    }
    else {
      this.set("isLoaded", true);
    }
  },

  didInsertElement() {
    this.securityEnabled();
  },

  actions: {
    invalidateSession() {
      triggerAnalytics('logout');
      this.get('session').invalidate();
    }
  }

});
<commit_msg>Get value from selected org in home-page<commit_after>import Ember from 'ember';
import triggerAnalytics from 'irene/utils/trigger-analytics';

const {inject: {service}} = Ember;

export default Ember.Component.extend({

  session: service(),

  isLoaded: false,
  isSecurityEnabled: false,
  isSecurityDashboard: false,
  organization: service('organization'),

  org: (function() {
    return this.get('organization.selected');
  }).property('organization.selected'),

  securityEnabled() {
    this.get("ajax").request("projects", {namespace: 'hudson-api'})
    .then(() => {
      this.set("isSecurityEnabled", true);
      this.securityDashboard();
    }, () => {
      this.set("isSecurityEnabled", false);
      this.securityDashboard();
    });
  },

  securityDashboard() {
    if(window.location.pathname.startsWith("/security")) {
      const isSecurityEnabled = this.get("isSecurityEnabled");
      if(isSecurityEnabled) {
        this.set("isSecurityDashboard", true);
      }
      else {
        Ember.getOwner(this).lookup('route:authenticated').transitionTo("authenticated.projects");
      }
      this.set("isLoaded", true);
    }
    else {
      this.set("isLoaded", true);
    }
  },

  didInsertElement() {
    this.securityEnabled();
  },

  actions: {
    invalidateSession() {
      triggerAnalytics('logout');
      this.get('session').invalidate();
    }
  }

});
<|endoftext|>


<commit_before>import {Observable as O} from 'rx';
import isolate from '@cycle/isolate';
import {div} from '@cycle/dom';

import {pluck} from '../../lib/utils';
import graphics from '../graphics';

import model from './model';
import view from './view';
import costPanel from './view/cost-panel';
import intent from './intent';

export default (responses) => {
  const {
    DOM,
    props$,
    data$,
  } = responses;

  const {isolateSource, isolateSink} = DOM;
  const actions = intent(isolateSource(DOM, 'please'));
  const state$ = model(props$, data$, actions);
  const vtree$ = view(state$).shareReplay(1);

  const stage = isolate(graphics, 'mygraphics')({
    DOM,
    props$: O.just({
      width: 1200,
      height: 600,
    }),
    camera$: O.just({x: 0, y: 0, zoom: 1}),
    bounds$: state$.map(pluck('bounds')),
    content$: isolateSink(vtree$, 'please'),
  });

  return {
    DOM: O.just(div([
      data$.map(costPanel),
      stage.DOM,
    ])),
    preventDefault: O.merge(
      actions.preventDefault,
      stage.preventDefault
    ),
  };
};
<commit_msg>rename isolation<commit_after>import {Observable as O} from 'rx';
import isolate from '@cycle/isolate';
import {div} from '@cycle/dom';

import {pluck} from '../../lib/utils';
import graphics from '../graphics';

import model from './model';
import view from './view';
import costPanel from './view/cost-panel';
import intent from './intent';

export default (responses) => {
  const {
    DOM,
    props$,
    data$,
  } = responses;

  const {isolateSource, isolateSink} = DOM;
  const actions = intent(isolateSource(DOM, 'graphicsContent'));
  const state$ = model(props$, data$, actions);
  const vtree$ = view(state$).shareReplay(1);

  const stage = isolate(graphics, 'mygraphics')({
    DOM,
    props$: O.just({
      width: 1200,
      height: 600,
    }),
    camera$: O.just({x: 0, y: 0, zoom: 1}),
    bounds$: state$.map(pluck('bounds')),
    content$: isolateSink(vtree$, 'graphicsContent'),
  });

  return {
    DOM: O.just(div([
      data$.map(costPanel),
      stage.DOM,
    ])),
    preventDefault: O.merge(
      actions.preventDefault,
      stage.preventDefault
    ),
  };
};
<|endoftext|>


<commit_before>import Auth0Lock from 'auth0-lock';
import {
  storeSecret
} from 'containers/Viewer/lib';
import {
  ORIGIN
} from 'components/Window/constants';

export const LOCK_CONTAINER_ID = 'lock-container';

let lock;

export function createAndShow(nextPathname, closable = true) {
  lock = createLock(nextPathname, closable);
  lock.show();
}

function createLock(nextPathname, closable) {
  const secret = createNonce();
  storeSecret(secret);
  return new Auth0Lock(process.env.AUTH0_CLIENT_ID, process.env.AUTH0_DOMAIN, {
    closable: closable,
    languageDictionary: {
      title: "Jotihunt inloggen"
    },
    auth: {
      redirectUrl: `${ORIGIN}/login/callback`,
      responseType: 'token',
      params: {
        state: JSON.stringify({
          secret,
          nextPathname,
        }),
      },
    },
  });
}

function createNonce() {
  let text = '';
  const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < randomLength(); i += 1) {
    text += charset.charAt(Math.floor(Math.random() * charset.length));
  }
  return text;
}

function randomLength() {
  const minLength = 30;
  const maxLength = 50;
  return Math.floor((Math.random() * maxLength) + minLength);
}<commit_msg>Disable rememberLastLogin<commit_after>import Auth0Lock from 'auth0-lock';
import {
  storeSecret
} from 'containers/Viewer/lib';
import {
  ORIGIN
} from 'components/Window/constants';

export const LOCK_CONTAINER_ID = 'lock-container';

let lock;

export function createAndShow(nextPathname, closable = true) {
  lock = createLock(nextPathname, closable);
  lock.show();
}

function createLock(nextPathname, closable) {
  const secret = createNonce();
  storeSecret(secret);
  return new Auth0Lock(process.env.AUTH0_CLIENT_ID, process.env.AUTH0_DOMAIN, {
    closable: closable,
    rememberLastLogin: false,
    languageDictionary: {
      title: "Jotihunt inloggen"
    },
    auth: {
      redirectUrl: `${ORIGIN}/login/callback`,
      responseType: 'token',
      params: {
        state: JSON.stringify({
          secret,
          nextPathname,
        }),
      },
    },
  });
}

function createNonce() {
  let text = '';
  const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < randomLength(); i += 1) {
    text += charset.charAt(Math.floor(Math.random() * charset.length));
  }
  return text;
}

function randomLength() {
  const minLength = 30;
  const maxLength = 50;
  return Math.floor((Math.random() * maxLength) + minLength);
}<|endoftext|>


<commit_before>import { connect } from "react-redux";
import { compose } from "redux";
import { Icon } from "@blueprintjs/core";

import withEditorProps from "../withEditorProps";
import specialCutsiteFilterOptions from "../constants/specialCutsiteFilterOptions";

import React from "react";
import "./style.css";
import Select from "react-select";

import map from "lodash/map";

export class CutsiteFilter extends React.Component {
  static defaultProps = {
    onChangeHook: () => {},
    filteredRestrictionEnzymes: [],
    filteredRestrictionEnzymesUpdate: [],
    allCutsites: { cutsitesByName: {} },
    sequenceData: {
      sequence: ""
    },
    dispatch: () => {}
  };

  render() {
    let {
      onChangeHook,
      style={},
      filteredRestrictionEnzymes,
      filteredRestrictionEnzymesUpdate,
      allCutsites: { cutsitesByName },
      sequenceData: { sequence: inputSequenceToTestAgainst },
      dispatch
      // ...rest
    } = this.props;
    // var {handleOpen, handleClose} = this
    let options = [
      ...map(specialCutsiteFilterOptions, opt => opt),
      ...Object.keys(cutsitesByName).map(function(key) {
        const cutNumber = cutsitesByName[key].length;
        return {
          label: (

              {" "}

{key}
{" "}

                 ({cutNumber} cut{cutNumber > 1 && "s"}){" "}

          ),
          value: key
        };
      })
    ];
    function openAddYourOwn() {
      dispatch({
        type: "ADD_YOUR_OWN_ENZYME_RESET",
        payload: {
          inputSequenceToTestAgainst,
          isOpen: true
        }
      });
    }
    return (

        <Select
          multi
          allowCreate
          noResultsText={

              No results found.{" "}
              <AddAdditionalEnzymeLink onClick={openAddYourOwn} />{" "}

          }
          placeholder="Filter cut sites..."
          options={options}
          optionRenderer={renderOptions}
          onChange={filteredRestrictionEnzymes => {
            if (
              filteredRestrictionEnzymes &&
              filteredRestrictionEnzymes.some(
                enzyme =>
                  enzyme.value === specialCutsiteFilterOptions.addYourOwn.value
              )
            ) {
              return openAddYourOwn();
            }
            onChangeHook && onChangeHook(filteredRestrictionEnzymes);
            filteredRestrictionEnzymesUpdate(filteredRestrictionEnzymes);
          }}
          value={filteredRestrictionEnzymes}
        />

    );
  }
}

export default compose(withEditorProps, connect())(CutsiteFilter);
function renderOptions({ label, value }) {
  if (value === "addYourOwn") {
    return <AddAdditionalEnzymeLink />;
  }

  return label;
}

function AddAdditionalEnzymeLink({ onClick }) {
  return (

      Add additional enzymes <Icon small icon="plus" />

  );
}
<commit_msg>fixing issue with cutsite drawing rendering above select menu<commit_after>import { connect } from "react-redux";
import { compose } from "redux";
import { Icon } from "@blueprintjs/core";

import withEditorProps from "../withEditorProps";
import specialCutsiteFilterOptions from "../constants/specialCutsiteFilterOptions";

import React from "react";
import "./style.css";
import Select from "react-select";

import map from "lodash/map";

export class CutsiteFilter extends React.Component {
  static defaultProps = {
    onChangeHook: () => {},
    filteredRestrictionEnzymes: [],
    filteredRestrictionEnzymesUpdate: [],
    allCutsites: { cutsitesByName: {} },
    sequenceData: {
      sequence: ""
    },
    dispatch: () => {}
  };

  render() {
    let {
      onChangeHook,
      style={},
      filteredRestrictionEnzymes,
      filteredRestrictionEnzymesUpdate,
      allCutsites: { cutsitesByName },
      sequenceData: { sequence: inputSequenceToTestAgainst },
      dispatch
      // ...rest
    } = this.props;
    // var {handleOpen, handleClose} = this
    let options = [
      ...map(specialCutsiteFilterOptions, opt => opt),
      ...Object.keys(cutsitesByName).map(function(key) {
        const cutNumber = cutsitesByName[key].length;
        return {
          label: (

              {" "}

{key}
{" "}

                 ({cutNumber} cut{cutNumber > 1 && "s"}){" "}

          ),
          value: key
        };
      })
    ];
    function openAddYourOwn() {
      dispatch({
        type: "ADD_YOUR_OWN_ENZYME_RESET",
        payload: {
          inputSequenceToTestAgainst,
          isOpen: true
        }
      });
    }
    return (

        <Select
          multi
          allowCreate
          wrapperStyle={{zIndex: 11}}
          noResultsText={

              No results found.{" "}
              <AddAdditionalEnzymeLink onClick={openAddYourOwn} />{" "}

          }
          placeholder="Filter cut sites..."
          options={options}
          optionRenderer={renderOptions}
          onChange={filteredRestrictionEnzymes => {
            if (
              filteredRestrictionEnzymes &&
              filteredRestrictionEnzymes.some(
                enzyme =>
                  enzyme.value === specialCutsiteFilterOptions.addYourOwn.value
              )
            ) {
              return openAddYourOwn();
            }
            onChangeHook && onChangeHook(filteredRestrictionEnzymes);
            filteredRestrictionEnzymesUpdate(filteredRestrictionEnzymes);
          }}
          value={filteredRestrictionEnzymes}
        />

    );
  }
}

export default compose(withEditorProps, connect())(CutsiteFilter);
function renderOptions({ label, value }) {
  if (value === "addYourOwn") {
    return <AddAdditionalEnzymeLink />;
  }

  return label;
}

function AddAdditionalEnzymeLink({ onClick }) {
  return (

      Add additional enzymes <Icon small icon="plus" />

  );
}
<|endoftext|>


<commit_before>/**
 * @overview
 *  Proposal for unifying API actions and constants into one place. Maybe.
 *  Goal is to get an easier-to-use way of creating the API event handlers,
 *  and a better way to look up events by path.
 *
 * @since 0.2.0
 */
import { Seq, Map } from 'immutable';
import { createAction } from 'redux-actions';
import { Internal } from '../records';
import { ApiEventPaths } from '../constants';
import kcsapiHandlers from '../actions/kcsapi';

/**
 * Ensure that the action handlers are mapped into {@link ApiHandler} records.
 * @type {Iterable<any, any>}
 */
export const handlers = Seq.Keyed(ApiEventPaths)
                           .flatMap((path, event) =>
                             Map.of(event, new Internal.ApiHandler({ path, event, handler: kcsapiHandlers[event] })));

/**
 * A non-`Seq` version of the @see findEventSeq function.
 * @param findPath
 * @returns {K|*}
 */
export const findEvent = (findPath) => {
  const pathRegex = new RegExp(`^${findPath}`);
  return ApiEventPaths.findKey((path) => pathRegex.test(path));
};

/**
 * Create a `Seq` of action handlers that is in a usable form for the Redux application.
 * @type {Iterable<any, any>}
 */
export const actionHandlers = Seq.Keyed(handlers)
                                 .flatMap((handlerRecord, event) =>
                                   Map.of(event, createAction(event, handlerRecord.handler)));
<commit_msg>Updated description<commit_after>/**
 * @overview
 *  API handler action creator
 *  Takes a key-value -pair representing the event to handle as key and its respective
 *  handler function as the value.
 *
 *  Event-to-URL mapping is done in `ApiEventPaths`.
 *
 * @since 0.2.0
 */
import { Seq, Map } from 'immutable';
import { createAction } from 'redux-actions';
import { Internal } from '../records';
import { ApiEventPaths } from '../constants';
import kcsapiHandlers from '../actions/kcsapi';

/**
 * Ensure that the action handlers are mapped into {@link ApiHandler} records.
 * @type {Iterable<any, any>}
 */
export const handlers = Seq.Keyed(ApiEventPaths)
                           .flatMap((path, event) =>
                             Map.of(event, new Internal.ApiHandler({ path, event, handler: kcsapiHandlers[event] })));

/**
 * A non-`Seq` version of the @see findEventSeq function.
 * @param findPath
 * @returns {K|*}
 */
export const findEvent = (findPath) => {
  const pathRegex = new RegExp(`^${findPath}`);
  return ApiEventPaths.findKey((path) => pathRegex.test(path));
};

/**
 * Create a `Seq` of action handlers that is in a usable form for the Redux application.
 * @type {Iterable<any, any>}
 */
export const actionHandlers = Seq.Keyed(handlers)
                                 .flatMap((handlerRecord, event) =>
                                   Map.of(event, createAction(event, handlerRecord.handler)));
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Controller.extend({
  version: Ember.inject.service(),

  currentVersion: Ember.computed('version', function() {
    return this.get('version').getVersion();
  }),

  actions: {
    visitWebsite() {
      var gui = window.requireNode('nw.gui');
      gui.Shell.openExternal("http://bloques.pilas-engine.com.ar");
    },
  }
});
<commit_msg>Reparando el link a la página del proyecto en navegadores.<commit_after>import Ember from 'ember';

export default Ember.Controller.extend({
  version: Ember.inject.service(),

  currentVersion: Ember.computed('version', function() {
    return this.get('version').getVersion();
  }),

  actions: {
    visitWebsite() {
      var url = "http://bloques.pilas-engine.com.ar";

      if (window['requireNode'] === undefined) {
        window.open(url);
      } else {
        var gui = window.requireNode('nw.gui');
        gui.Shell.openExternal(url);
      }
    },
  }
});
<|endoftext|>


<commit_before>'use strict';

var db           = require('magic-db')
  , express      = require('express')
  , stylus       = require('stylus')
  , bodyParser   = require('body-parser')
  , cookieParser = require('cookie-parser')
  , compression  = require('compression')
  , favicon      = require('serve-favicon')
  , fs           = require('fs')
  , morgan       = require('morgan')
  , errorHandler = require('magic-errorHandler')
  , headers      = require('magic-headers')
  , log          = require('magic-log')
  , auth         = require('magic-auth')
  , path         = require('path')
  , router       = require('magic-router')
  , sslRedirect  = require('magic-ssl')
;

module.exports = function(M, S, dir) {
  var css         = ( S.get('css') || stylus )
    , env         = S.get('env') || 'production'
    , dbConf      = S.get('db') || false
    , faviconPath = path.join(dir, 'public', 'favicon.ico')
    , dirs        = S.get('dirs') || {
        public: path.join(dir, 'public')
      , views : path.join(dir, 'views')
    }
  ;

  if ( ! S.get('allowHttp') && S.get('env') === 'production' ) {
   // S.use(sslRedirect);
  }

  //set expiry headers
  S.use(headers);

  //fs.existsSync only gets called once
  if ( ! S.get('faviconExistanceCheck') ) {
    S.set('faviconExistanceCheck', true);
    S.set('faviconExists', fs.existsSync(faviconPath));
  }

  if ( S.get('faviconExists') ) {
    S.use( favicon(faviconPath) );
  }

  S.set('views', dirs.views);
  S.set('view engine', S.get('view engine') || 'jade');

  S.use(compression({ threshold: 128 }));

  S.use( css.middleware(dirs.public, {maxAge: '1d'}) );
  S.use( express.static(dirs.public, {maxAge: '1d'}) );

  if ( S.get('db') ) {
    let dbConf = S.get('db')
      , schema = db(dbConf);
    ;

    S.set('schema', schema);
  }

  //logging
  S.use(morgan('combined'));

  //if host sets bodyparser to true, init it
  if ( S.get('bodyParser') ) {
    S.use(bodyParser.json());
    S.use(bodyParser.urlencoded({ extended: false }));
  }

  //if host sets cookieparser to true, init it:
  if ( S.get('cookieParser') ) {
    S.use(cookieParser());
  }

  if ( S.get('useAuth') ) {
    S.use(function (req, res, next) {
       auth.routes(S, req, res, next);
    });
  }

  //load host specific routes
  if ( S.get('routes') ) {
    let routes = S.get('routes');

    if ( typeof routes === 'array' || typeof routes === 'object' ) {
      for (var route in routes ) {
        S.use(route);
      }
    } else if ( typeof routes === 'function' ) {
      S.use( routes );
    }
  }

  S.use(router);
  S.use(errorHandler);

  return S;
}
<commit_msg>removed unneeded line<commit_after>'use strict';

var db           = require('magic-db')
  , express      = require('express')
  , stylus       = require('stylus')
  , bodyParser   = require('body-parser')
  , cookieParser = require('cookie-parser')
  , compression  = require('compression')
  , favicon      = require('serve-favicon')
  , fs           = require('fs')
  , morgan       = require('morgan')
  , errorHandler = require('magic-errorHandler')
  , headers      = require('magic-headers')
  , log          = require('magic-log')
  , auth         = require('magic-auth')
  , path         = require('path')
  , router       = require('magic-router')
  , sslRedirect  = require('magic-ssl')
;

module.exports = function(M, S, dir) {
  var css         = ( S.get('css') || stylus )
    , env         = S.get('env') || 'production'
    , dbConf      = S.get('db') || false
    , faviconPath = path.join(dir, 'public', 'favicon.ico')
    , dirs        = S.get('dirs') || {
        public: path.join(dir, 'public')
      , views : path.join(dir, 'views')
    }
  ;

  if ( ! S.get('allowHttp') && S.get('env') === 'production' ) {
   // S.use(sslRedirect);
  }

  //set expiry headers
  S.use(headers);

  //fs.existsSync only gets called once
  if ( ! S.get('faviconExistanceCheck') ) {
    S.set('faviconExistanceCheck', true);
    S.set('faviconExists', fs.existsSync(faviconPath));
  }

  if ( S.get('faviconExists') ) {
    S.use( favicon(faviconPath) );
  }

  S.set('views', dirs.views);
  S.set('view engine', S.get('view engine') || 'jade');

  S.use(compression({ threshold: 128 }));

  S.use( css.middleware(dirs.public, {maxAge: '1d'}) );
  S.use( express.static(dirs.public, {maxAge: '1d'}) );

  if ( S.get('db') ) {
    let dbConf = S.get('db')
      , schema = db(dbConf);
    ;

    S.set('schema', schema);
  }

  //logging
  S.use(morgan('combined'));

  //if host sets bodyparser to true, init it
  if ( S.get('bodyParser') ) {
    S.use(bodyParser.json());
    S.use(bodyParser.urlencoded({ extended: false }));
  }

  //if host sets cookieparser to true, init it:
  if ( S.get('cookieParser') ) {
    S.use(cookieParser());
  }

  if ( S.get('useAuth') ) {
    S.use(function (req, res, next) {
       auth.routes(S, req, res, next);
    });
  }

  //load host specific routes
  if ( S.get('routes') ) {
    let routes = S.get('routes');

    if ( typeof routes === 'array' || typeof routes === 'object' ) {
      for (var route in routes ) {
        S.use(route);
      }
    } else if ( typeof routes === 'function' ) {
      S.use( routes );
    }
  }

  S.use(router);
  S.use(errorHandler);

  return S;
}
<|endoftext|>


<commit_before>import { merge } from './updates.js';
import * as symbols from './symbols.js';

// Symbols for private data members.
const documentScrollingDisabledKey = Symbol('documentScrollingDisabled');
const previousBodyOverflowKey = Symbol('previousBodyStyleOverflow');
const previousDocumentMarginRightKey = Symbol('previousDocumentMarginRight');

/**
 * This mixin blocks various user interactions to make an overlay behave like a
 * modal dialog. This mixin is generally used in conjunction with a backdrop.
 *
 * This mixin expects the component to provide:
 *
 * * An open/close API compatible with `OverlayMixin`.
 *
 * The mixin provides these features to the component:
 *
 * * Disables scrolling on the background document. **This is a global
 *   side-effect of opening the component.**
 * * A default ARIA role of `dialog`.
 * * Closes the element if user presses the Esc key.
 *
 * For modeless overlays, see `PopupModalityMixin` instead.
 *
 * @module DialogModalityMixin
 */
export default function DialogModalityMixin(Base) {
  return class DialogModality extends Base {

    componentDidUpdate(previousState) {
      if (super.componentDidUpdate) { super.componentDidUpdate(previousState); }
      if (this.opened && !this[documentScrollingDisabledKey]) {
        disableDocumentScrolling(this);
        this[documentScrollingDisabledKey] = true;
      } else if (this.closed && this[documentScrollingDisabledKey]) {
        enableDocumentScrolling(this);
        this[documentScrollingDisabledKey] = false;
      }
    }

    disconnectedCallback() {
      if (super.disconnectedCallback) { super.disconnectedCallback(); }
      enableDocumentScrolling(this);
    }

    get defaultState() {
      return Object.assign({}, super.defaultState, {
        role: 'dialog'
      });
    }

    [symbols.keydown](event) {
      let handled = false;

      switch (event.key) {

        case 'Escape':
          // Close on Esc key.
          this.close();
          handled = true;
          break;
      }

      // Prefer mixin result if it's defined, otherwise use base result.
      return handled || (super[symbols.keydown] && super[symbols.keydown](event)) || false;
    }

    get updates() {
      const original = this.state.original;
      const role = original.attributes && original.attributes.role || this.state.role;
      return merge(super.updates, {
        attributes: {
          role
        }
      });
    }

  }
}

// Mark body as non-scrollable, to absorb space bar keypresses and other
// means of scrolling the top-level document.
function disableDocumentScrolling(element) {
  const scrollBarWidth = window.innerWidth - document.body.clientWidth;
  element[previousBodyOverflowKey] = document.body.style.overflow;
  element[previousDocumentMarginRightKey] = scrollBarWidth > 0 ?
    document.documentElement.style.marginRight :
    null;
  document.body.style.overflow = 'hidden';
  if (scrollBarWidth > 0) {
    document.documentElement.style.marginRight = `${scrollBarWidth}px`;
  }
}

function enableDocumentScrolling(element) {
  if (element[previousBodyOverflowKey] != null) {
    document.body.style.overflow = element[previousBodyOverflowKey];
    element[previousBodyOverflowKey] = null;
  }
  if (element[previousDocumentMarginRightKey] != null) {
    document.documentElement.style.marginRight = element[previousDocumentMarginRightKey];
    element[previousDocumentMarginRightKey] = null;
  }
}
<commit_msg>More precise calculation of document scroll bar width<commit_after>import { merge } from './updates.js';
import * as symbols from './symbols.js';

// Symbols for private data members.
const documentScrollingDisabledKey = Symbol('documentScrollingDisabled');
const previousBodyOverflowKey = Symbol('previousBodyStyleOverflow');
const previousDocumentMarginRightKey = Symbol('previousDocumentMarginRight');

/**
 * This mixin blocks various user interactions to make an overlay behave like a
 * modal dialog. This mixin is generally used in conjunction with a backdrop.
 *
 * This mixin expects the component to provide:
 *
 * * An open/close API compatible with `OverlayMixin`.
 *
 * The mixin provides these features to the component:
 *
 * * Disables scrolling on the background document. **This is a global
 *   side-effect of opening the component.**
 * * A default ARIA role of `dialog`.
 * * Closes the element if user presses the Esc key.
 *
 * For modeless overlays, see `PopupModalityMixin` instead.
 *
 * @module DialogModalityMixin
 */
export default function DialogModalityMixin(Base) {
  return class DialogModality extends Base {

    componentDidUpdate(previousState) {
      if (super.componentDidUpdate) { super.componentDidUpdate(previousState); }
      if (this.opened && !this[documentScrollingDisabledKey]) {
        disableDocumentScrolling(this);
        this[documentScrollingDisabledKey] = true;
      } else if (this.closed && this[documentScrollingDisabledKey]) {
        enableDocumentScrolling(this);
        this[documentScrollingDisabledKey] = false;
      }
    }

    disconnectedCallback() {
      if (super.disconnectedCallback) { super.disconnectedCallback(); }
      enableDocumentScrolling(this);
    }

    get defaultState() {
      return Object.assign({}, super.defaultState, {
        role: 'dialog'
      });
    }

    [symbols.keydown](event) {
      let handled = false;

      switch (event.key) {

        case 'Escape':
          // Close on Esc key.
          this.close();
          handled = true;
          break;
      }

      // Prefer mixin result if it's defined, otherwise use base result.
      return handled || (super[symbols.keydown] && super[symbols.keydown](event)) || false;
    }

    get updates() {
      const original = this.state.original;
      const role = original.attributes && original.attributes.role || this.state.role;
      return merge(super.updates, {
        attributes: {
          role
        }
      });
    }

  }
}

// Mark body as non-scrollable, to absorb space bar keypresses and other
// means of scrolling the top-level document.
function disableDocumentScrolling(element) {
  const documentWidth = document.documentElement.clientWidth;
  const scrollBarWidth = window.innerWidth - documentWidth;
  element[previousBodyOverflowKey] = document.body.style.overflow;
  element[previousDocumentMarginRightKey] = scrollBarWidth > 0 ?
    document.documentElement.style.marginRight :
    null;
  document.body.style.overflow = 'hidden';
  if (scrollBarWidth > 0) {
    document.documentElement.style.marginRight = `${scrollBarWidth}px`;
  }
}

function enableDocumentScrolling(element) {
  if (element[previousBodyOverflowKey] != null) {
    document.body.style.overflow = element[previousBodyOverflowKey];
    element[previousBodyOverflowKey] = null;
  }
  if (element[previousDocumentMarginRightKey] != null) {
    document.documentElement.style.marginRight = element[previousDocumentMarginRightKey];
    element[previousDocumentMarginRightKey] = null;
  }
}
<|endoftext|>


<commit_before>import {ExampleCtrl} from './example';
import './index';

describe('Example module', function() {
    var $controllerProvider, scope = {}, $rootScope, $controller;

    beforeEach(angular.mock.module('example'));

    beforeEach(angular.mock.module(function(_$controllerProvider_) {
        $controllerProvider = _$controllerProvider_;
    }));

    describe('Help controller', function() {

        beforeEach(angular.mock.inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $controller = $injector.get('$controller');
            $controllerProvider.register('ExampleCtrl', ExampleCtrl);

            scope = $rootScope.$new();

            $controller('ExampleCtrl as Example', {
                $scope: scope,
                data: [1, 2, 3, 4, 5, 6]
            });
        }));

        it('should load example data', function() {
            expect(scope.Example.exampleData).to.not.be.undefined();
        });

        it('should load example data as an array', function() {
            expect(scope.Example.exampleData).to.be.an('array');
        });

        it('should have a property called data that returns exampleData', function() {
            expect(scope.Example.data).to.be.an('array');
            expect(scope.Example.data).to.deep.equal(scope.Example.exampleData);
        });

        it('should have a method called someMethod that returns the double for each value', function() {
            expect(scope.Example.someMethod()).to.deep.equal([2, 4, 6, 8, 10, 12]);
        });
    });
});
<commit_msg>fix(example): Fix test<commit_after>import {ExampleCtrl} from './example';
import './index';

describe('Example module', function() {
    var $controllerProvider, scope = {}, $rootScope, $controller;

    beforeEach(angular.mock.module('example'));

    beforeEach(angular.mock.module(function(_$controllerProvider_) {
        $controllerProvider = _$controllerProvider_;
    }));

    describe('Help controller', function() {

        beforeEach(angular.mock.inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $controller = $injector.get('$controller');
            $controllerProvider.register('ExampleCtrl', ExampleCtrl);

            scope = $rootScope.$new();

            $controller('ExampleCtrl as Example', {
                $scope: scope,
                data: [1, 2, 3, 4, 5, 6]
            });
        }));

        it('should load example data', function() {
            expect(scope.Example.exampleData).to.not.be.undefined;
        });

        it('should load example data as an array', function() {
            expect(scope.Example.exampleData).to.be.an('array');
        });

        it('should have a property called data that returns exampleData', function() {
            expect(scope.Example.data).to.be.an('array');
            expect(scope.Example.data).to.deep.equal(scope.Example.exampleData);
        });

        it('should have a method called someMethod that returns the double for each value', function() {
            expect(scope.Example.someMethod()).to.deep.equal([2, 4, 6, 8, 10, 12]);
        });
    });
});
<|endoftext|>