<commit_before>define(["Ti/_/Layouts/Base", "Ti/_/declare", "Ti/UI", "Ti/_/lang", "Ti/_/style"], function(Base, declare, UI, lang, style) {

	var isDef = lang.isDef,
		setStyle = style.set;

	return declare("Ti._.Layouts.Horizontal", Base, {

		_doLayout: function(element, width, height, isWidthSize, isHeightSize) {
			var computedSize = this._computedSize = {width: 0, height: 0},
				children = element.children,
				child,
				i, j,
				layoutCoefficients,
				widthLayoutCoefficients, heightLayoutCoefficients, sandboxWidthLayoutCoefficients, sandboxHeightLayoutCoefficients, topLayoutCoefficients, leftLayoutCoefficients,
				childSize,
				measuredWidth, measuredHeight, measuredSandboxHeight, measuredSandboxWidth, measuredLeft, measuredTop,
				pixelUnits = "px",
				runningHeight = 0, runningWidth = 0,
				rows = [[]], row,
				rowHeights = [], rowHeight,
				deferredTopCalculations = [];

			// Calculate horizontal size and position for the children
			for(i = 0; i < children.length; i++) {

				child = element.children[i];
				if (this.verifyChild(child,element)) {
					//if (child._markedForLayout) {
					child._needsMeasuring && this._measureNode(child);

					layoutCoefficients = child._layoutCoefficients;
					widthLayoutCoefficients = layoutCoefficients.width;
					heightLayoutCoefficients = layoutCoefficients.height;
					sandboxWidthLayoutCoefficients = layoutCoefficients.sandboxWidth;
					sandboxHeightLayoutCoefficients = layoutCoefficients.sandboxHeight;
					leftLayoutCoefficients = layoutCoefficients.left;

					measuredWidth = widthLayoutCoefficients.x1 * width + widthLayoutCoefficients.x2 * (width - runningWidth) + widthLayoutCoefficients.x3;
					measuredHeight = heightLayoutCoefficients.x1 * height + heightLayoutCoefficients.x2;

					if (child._getContentSize) {
						childSize = child._getContentSize();
					} else {
						childSize = child._layout._doLayout(
							child,
							isNaN(measuredWidth) ? width : measuredWidth,
							isNaN(measuredHeight) ? height : measuredHeight,
							isNaN(measuredWidth),
							isNaN(measuredHeight));
					}
					isNaN(measuredWidth) && (measuredWidth = childSize.width);
					isNaN(measuredHeight) && (measuredHeight = childSize.height);

					measuredSandboxWidth = sandboxWidthLayoutCoefficients.x1 * width + sandboxWidthLayoutCoefficients.x2 + measuredWidth;

					measuredLeft = leftLayoutCoefficients.x1 * width + leftLayoutCoefficients.x2 + runningWidth;
					if (!isWidthSize && Math.floor(measuredSandboxWidth + runningWidth) > Math.ceil(width)) {
						rows.push([]);
						measuredLeft -= runningWidth;
						runningWidth = 0;
					}
					rows[rows.length - 1].push(child);
					runningWidth += measuredSandboxWidth;
					runningWidth > computedSize.width && (computedSize.width = runningWidth);

					child._newMeasuredWidth = measuredWidth;
					child._newMeasuredHeight = measuredHeight; // Height is only set if auto, otherwise it is calculated in the next phase
					child._newMeasuredSandboxWidth = measuredSandboxWidth;
					child._newMeasuredLeft = measuredLeft;
					//}
				}
			}

			// Calculate vertical size and position for the children
			runningHeight = 0;
			for(i = 0; i < rows.length; i++) {
				row = rows[i];
				rowHeight = 0;
				for (j = 0; j < row.length; j++) {
					child = row[j];

					if (this.verifyChild(child,element)) {
						//if (child._markedForLayout) {
						layoutCoefficients = child._layoutCoefficients;
						topLayoutCoefficients = layoutCoefficients.top;
						sandboxHeightLayoutCoefficients = layoutCoefficients.sandboxHeight;
						measuredHeight = child._newMeasuredHeight;

						if (topLayoutCoefficients.x2 !== 0) {
							deferredTopCalculations.push(child);
							measuredTop = 0; // Temporary for use in calculating row height
						} else {
							child._newMeasuredTop = measuredTop = topLayoutCoefficients.x1 * height + topLayoutCoefficients.x3 * measuredHeight + topLayoutCoefficients.x4 + runningHeight;
						}

						child._measuredSandboxHeight = measuredSandboxHeight = sandboxHeightLayoutCoefficients.x1 * height + sandboxHeightLayoutCoefficients.x2 + measuredHeight + measuredTop;
						rowHeight < measuredSandboxHeight && (rowHeight = measuredSandboxHeight);
						//}
					}
				}
				rowHeights.push(rowHeight);
				runningHeight += rowHeight;
			}
			computedSize.height = runningHeight;

			// Second pass, if necessary, to determine the top values
			runningHeight = 0;
			for(i = 0; i < rows.length; i++) {
				row = rows[i];
				rowHeight = rowHeights[i];
				for (j = 0; j < row.length; j++) {
					child = row[j];

					if (this.verifyChild(child,element) && ~deferredTopCalculations.indexOf(child)) {
						//if (child._markedForLayout) {
							measuredHeight = child._newMeasuredHeight;
							topLayoutCoefficients = child._layoutCoefficients.top;
							child._newMeasuredTop = topLayoutCoefficients.x1 * height + topLayoutCoefficients.x2 * rowHeight + topLayoutCoefficients.x3 * measuredHeight + topLayoutCoefficients.x4 + runningHeight;
						//}
					}
				}
				runningHeight += rowHeight;
			}

			// Position the children
			for(i = 0; i < children.length; i++) {

				UI._elementLayoutCount++;

				// Set and store the dimensions
				child = children[i];
				setStyle(child.domNode, {
					zIndex: child.zIndex | 0,
					left: child._measuredLeft + pixelUnits,
					top: child._measuredTop + pixelUnits,
					width: child._measuredWidth + pixelUnits,
					height: child._measuredHeight + pixelUnits
				});
			}

			return computedSize;
		},

		_measureNode: function(node) {

			node._needsMeasuring = false;

			// Pre-processing
			var getValueType = this.getValueType,
				computeValue = this.computeValue,

				width = node.width === UI.INHERIT ? node._getInheritedWidth() : node.width,

				height = node.height === UI.INHERIT ? node._getInheritedHeight() : node.height,

				left = node.left,
				leftType = getValueType(left),
				leftValue = computeValue(left, leftType),

				right = node.right,
				rightType = getValueType(right),
				rightValue = computeValue(right, rightType),

				top = node.top,
				topType = getValueType(top),
				topValue = computeValue(top, topType),

				bottom = node.bottom,
				bottomType = getValueType(bottom),
				bottomValue = computeValue(bottom, bottomType),

				x1, x2, x3, x4,

				layoutCoefficients = node._layoutCoefficients,
				widthLayoutCoefficients = layoutCoefficients.width,
				heightLayoutCoefficients = layoutCoefficients.height,
				sandboxWidthLayoutCoefficients = layoutCoefficients.sandboxWidth,
				sandboxHeightLayoutCoefficients = layoutCoefficients.sandboxHeight,
				leftLayoutCoefficients = layoutCoefficients.left,
				topLayoutCoefficients = layoutCoefficients.top;

			// Apply the default width and pre-process width and height
			!isDef(width) && (width = node._defaultWidth === UI.INHERIT ? node._getInheritedWidth() : node._defaultWidth);
			!isDef(height) && (height = node._defaultHeight === UI.INHERIT ? node._getInheritedHeight() : node._defaultHeight);
			var widthType = getValueType(width),
				widthValue = computeValue(width, widthType),
				heightType = getValueType(height),
				heightValue = computeValue(height, heightType);

			// Width rule calculation
			x1 = x2 = x3 = 0;
			if (widthType === UI.SIZE) {
				x1 = x2 = x3 = NaN;
			} else if (widthType === UI.FILL) {
				x2 = 1;
				leftType === "%" && (x1 = -leftValue);
				leftType === "#" && (x3 = -leftValue);
				rightType === "%" && (x1 = -rightValue);
				rightType === "#" && (x3 = -rightValue);
			} else if (widthType === "%") {
				x1 = widthValue;
			} else if (widthType === "#") {
				x3 = widthValue;
			}
			widthLayoutCoefficients.x1 = x1;
			widthLayoutCoefficients.x2 = x2;
			widthLayoutCoefficients.x3 = x3;

			// Sandbox width rule calculation
			x1 = x2 = 0;
			leftType === "%" && (x1 = leftValue);
			leftType === "#" && (x2 = leftValue);
			rightType === "%" && (x1 += rightValue);
			rightType === "#" && (x2 += rightValue);
			sandboxWidthLayoutCoefficients.x1 = x1;
			sandboxWidthLayoutCoefficients.x2 = x2;

			// Height rule calculation
			x1 = x2 = 0;
			if (heightType === UI.SIZE) {
				x1 = x2 = NaN;
			} else if (heightType === UI.FILL) {
				x1 = 1;
				topType === "%" && (x1 = -topValue);
				topType === "#" && (x2 = -topValue);
				bottomType === "%" && (x1 = -bottomValue);
				bottomType === "#" && (x2 = -bottomValue);
			} else if (heightType === "%") {
				x1 = heightValue;
			} else if (heightType === "#") {
				x2 = heightValue;
			}
			heightLayoutCoefficients.x1 = x1;
			heightLayoutCoefficients.x2 = x2;

			// Sandbox height rule calculation
			sandboxHeightLayoutCoefficients.x1 = bottomType === "%" ? bottomValue : 0;
			sandboxHeightLayoutCoefficients.x2 = bottomType === "#" ? bottomValue : 0;

			// Left rule calculation
			leftLayoutCoefficients.x1 = leftType === "%" ? leftValue : 0;
			leftLayoutCoefficients.x2 = leftType === "#" ? leftValue : 0;

			// Top rule calculation
			x1 = x2 = x3 = x4 = 0;
			if (topType === "%") {
				x1 = topValue;
			} else if(topType === "#") {
				x4 = topValue;
			} else {
				switch(this._defaultRowAlignment) {
					case "center":
						x2 = 0.5;
						x3 = -0.5;
						break;
					case "end":
						x2 = 1;
						x3 = -1;
				}
			}
			topLayoutCoefficients.x1 = x1;
			topLayoutCoefficients.x2 = x2;
			topLayoutCoefficients.x3 = x3;
			topLayoutCoefficients.x4 = x4;
		},

		_defaultHorizontalAlignment: "start",

		_defaultVerticalAlignment: "start",

		_defaultRowAlignment: "center"

	});

});
<commit_msg>[TIMOB-8275] Fixed some bugs in horizontal layout<commit_after>define(["Ti/_/Layouts/Base", "Ti/_/declare", "Ti/UI", "Ti/_/lang", "Ti/_/style"], function(Base, declare, UI, lang, style) {

	var isDef = lang.isDef,
		setStyle = style.set;

	return declare("Ti._.Layouts.Horizontal", Base, {

		_doLayout: function(element, width, height, isWidthSize, isHeightSize) {
			var computedSize = this._computedSize = {width: 0, height: 0},
				children = element.children,
				child,
				i, j,
				layoutCoefficients,
				widthLayoutCoefficients, heightLayoutCoefficients, sandboxWidthLayoutCoefficients, sandboxHeightLayoutCoefficients, topLayoutCoefficients, leftLayoutCoefficients,
				childSize,
				measuredWidth, measuredHeight, measuredSandboxHeight, measuredSandboxWidth, measuredLeft, measuredTop,
				pixelUnits = "px",
				runningHeight = 0, runningWidth = 0,
				rows = [[]], row,
				rowHeights = [], rowHeight,
				deferredTopCalculations = [],
				deferHeight,
				sizeHeight;

			// Calculate horizontal size and position for the children
			for(i = 0; i < children.length; i++) {

				child = element.children[i];
				if (this.verifyChild(child,element)) {
					//if (child._markedForLayout) {
					child._needsMeasuring && this._measureNode(child);

					layoutCoefficients = child._layoutCoefficients;
					widthLayoutCoefficients = layoutCoefficients.width;
					heightLayoutCoefficients = layoutCoefficients.height;
					sandboxWidthLayoutCoefficients = layoutCoefficients.sandboxWidth;
					sandboxHeightLayoutCoefficients = layoutCoefficients.sandboxHeight;
					leftLayoutCoefficients = layoutCoefficients.left;

					deferHeight = heightLayoutCoefficients.x2 === 0;
					sizeHeight = !deferHeight && isNaN(measuredHeight);

					measuredWidth = widthLayoutCoefficients.x1 * width + widthLayoutCoefficients.x2 * (width - runningWidth) + widthLayoutCoefficients.x3;
					measuredHeight = deferHeight ? heightLayoutCoefficients.x1 * height + heightLayoutCoefficients.x3 : NaN;

					if (child._getContentSize) {
						childSize = child._getContentSize();
					} else {
						childSize = child._layout._doLayout(
							child,
							isNaN(measuredWidth) ? width : measuredWidth,
							sizeHeight ? height : measuredHeight,
							isNaN(measuredWidth),
							isNaN(measuredHeight));
					}
					isNaN(measuredWidth) && (measuredWidth = childSize.width);
					sizeHeight && (measuredHeight = childSize.height);

					measuredSandboxWidth = sandboxWidthLayoutCoefficients.x1 * width + sandboxWidthLayoutCoefficients.x2 + measuredWidth;

					measuredLeft = leftLayoutCoefficients.x1 * width + leftLayoutCoefficients.x2 + runningWidth;
					if (!isWidthSize && Math.floor(measuredSandboxWidth + runningWidth) > Math.ceil(width)) {
						rows.push([]);
						measuredLeft -= runningWidth;
						runningWidth = 0;
					}
					rows[rows.length - 1].push(child);
					runningWidth += measuredSandboxWidth;
					runningWidth > computedSize.width && (computedSize.width = runningWidth);

					child._measuredWidth = measuredWidth;
					child._measuredHeight = measuredHeight;
					child._measuredSandboxWidth = measuredSandboxWidth;
					child._measuredLeft = measuredLeft;
					//}
				}
			}

			// Calculate vertical size and position for the children
			runningHeight = 0;
			for(i = 0; i < rows.length; i++) {
				row = rows[i];
				rowHeight = 0;
				for (j = 0; j < row.length; j++) {
					child = row[j];

					if (this.verifyChild(child,element)) {
						//if (child._markedForLayout) {
						layoutCoefficients = child._layoutCoefficients;
						topLayoutCoefficients = layoutCoefficients.top;
						sandboxHeightLayoutCoefficients = layoutCoefficients.sandboxHeight;
						measuredHeight = child._measuredHeight;
						isNaN(measuredHeight) && (measuredHeight = child._measuredHeight = heightLayoutCoefficients.x1 * height + heightLayoutCoefficients.x2 * (height - runningHeight) + heightLayoutCoefficients.x3);

						if (topLayoutCoefficients.x2 !== 0) {
							deferredTopCalculations.push(child);
							measuredTop = 0; // Temporary for use in calculating row height
						} else {
							child._measuredTop = measuredTop = topLayoutCoefficients.x1 * height + topLayoutCoefficients.x3 * measuredHeight + topLayoutCoefficients.x4 + runningHeight;
						}

						child._measuredSandboxHeight = measuredSandboxHeight = sandboxHeightLayoutCoefficients.x1 * height + sandboxHeightLayoutCoefficients.x2 + measuredHeight + measuredTop;
						rowHeight < measuredSandboxHeight && (rowHeight = measuredSandboxHeight);
						//}
					}
				}
				rowHeights.push(rowHeight);
				runningHeight += rowHeight;
			}

			// Second pass, if necessary, to determine the top values
			runningHeight = 0;
			for(i = 0; i < rows.length; i++) {
				row = rows[i];
				rowHeight = rowHeights[i];
				for (j = 0; j < row.length; j++) {
					child = row[j];

					if (this.verifyChild(child,element) && ~deferredTopCalculations.indexOf(child)) {
						//if (child._markedForLayout) {
							measuredHeight = child._measuredHeight;
							topLayoutCoefficients = child._layoutCoefficients.top;
							child._measuredTop = topLayoutCoefficients.x1 * height + topLayoutCoefficients.x2 * rowHeight + topLayoutCoefficients.x3 * measuredHeight + topLayoutCoefficients.x4 + runningHeight;
						//}
					}
				}
				runningHeight += rowHeight;
			}
			computedSize.height = runningHeight;

			// Position the children
			for(i = 0; i < children.length; i++) {

				UI._elementLayoutCount++;

				// Set and store the dimensions
				child = children[i];
				setStyle(child.domNode, {
					zIndex: child.zIndex | 0,
					left: child._measuredLeft + pixelUnits,
					top: child._measuredTop + pixelUnits,
					width: child._measuredWidth + pixelUnits,
					height: child._measuredHeight + pixelUnits
				});
			}

			return computedSize;
		},

		_measureNode: function(node) {

			node._needsMeasuring = false;

			// Pre-processing
			var getValueType = this.getValueType,
				computeValue = this.computeValue,

				width = node.width === UI.INHERIT ? node._getInheritedWidth() : node.width,

				height = node.height === UI.INHERIT ? node._getInheritedHeight() : node.height,

				left = node.left,
				leftType = getValueType(left),
				leftValue = computeValue(left, leftType),

				right = node.right,
				rightType = getValueType(right),
				rightValue = computeValue(right, rightType),

				top = node.top,
				topType = getValueType(top),
				topValue = computeValue(top, topType),

				bottom = node.bottom,
				bottomType = getValueType(bottom),
				bottomValue = computeValue(bottom, bottomType),

				x1, x2, x3, x4,

				layoutCoefficients = node._layoutCoefficients,
				widthLayoutCoefficients = layoutCoefficients.width,
				heightLayoutCoefficients = layoutCoefficients.height,
				sandboxWidthLayoutCoefficients = layoutCoefficients.sandboxWidth,
				sandboxHeightLayoutCoefficients = layoutCoefficients.sandboxHeight,
				leftLayoutCoefficients = layoutCoefficients.left,
				topLayoutCoefficients = layoutCoefficients.top;

			// Apply the default width and pre-process width and height
			!isDef(width) && (width = node._defaultWidth === UI.INHERIT ? node._getInheritedWidth() : node._defaultWidth);
			!isDef(height) && (height = node._defaultHeight === UI.INHERIT ? node._getInheritedHeight() : node._defaultHeight);
			var widthType = getValueType(width),
				widthValue = computeValue(width, widthType),
				heightType = getValueType(height),
				heightValue = computeValue(height, heightType);

			// Width rule calculation
			x1 = x2 = x3 = 0;
			if (widthType === UI.SIZE) {
				x1 = x2 = x3 = NaN;
			} else if (widthType === UI.FILL) {
				x2 = 1;
				leftType === "%" && (x1 = -leftValue);
				leftType === "#" && (x3 = -leftValue);
				rightType === "%" && (x1 = -rightValue);
				rightType === "#" && (x3 = -rightValue);
			} else if (widthType === "%") {
				x1 = widthValue;
			} else if (widthType === "#") {
				x3 = widthValue;
			}
			widthLayoutCoefficients.x1 = x1;
			widthLayoutCoefficients.x2 = x2;
			widthLayoutCoefficients.x3 = x3;

			// Sandbox width rule calculation
			x1 = x2 = 0;
			leftType === "%" && (x1 = leftValue);
			leftType === "#" && (x2 = leftValue);
			rightType === "%" && (x1 += rightValue);
			rightType === "#" && (x2 += rightValue);
			sandboxWidthLayoutCoefficients.x1 = x1;
			sandboxWidthLayoutCoefficients.x2 = x2;

			// Height rule calculation
			x1 = x2 = x3 = 0;
			if (heightType === UI.SIZE) {
				x1 = x2 = x3 = NaN;
			} else if (heightType === UI.FILL) {
				x2 = 1;
				topType === "%" && (x1 = -topValue);
				topType === "#" && (x3 = -topValue);
			} else if (heightType === "%") {
				x1 = heightValue;
			} else if (heightType === "#") {
				x3 = heightValue;
			}
			heightLayoutCoefficients.x1 = x1;
			heightLayoutCoefficients.x2 = x2;
			heightLayoutCoefficients.x3 = x3;

			// Sandbox height rule calculation
			sandboxHeightLayoutCoefficients.x1 = bottomType === "%" ? bottomValue : 0;
			sandboxHeightLayoutCoefficients.x2 = bottomType === "#" ? bottomValue : 0;

			// Left rule calculation
			leftLayoutCoefficients.x1 = leftType === "%" ? leftValue : 0;
			leftLayoutCoefficients.x2 = leftType === "#" ? leftValue : 0;

			// Top rule calculation
			x1 = x2 = x3 = x4 = 0;
			if (topType === "%") {
				x1 = topValue;
			} else if(topType === "#") {
				x4 = topValue;
			} else {
				switch(this._defaultRowAlignment) {
					case "center":
						x2 = 0.5;
						x3 = -0.5;
						break;
					case "end":
						x2 = 1;
						x3 = -1;
				}
			}
			topLayoutCoefficients.x1 = x1;
			topLayoutCoefficients.x2 = x2;
			topLayoutCoefficients.x3 = x3;
			topLayoutCoefficients.x4 = x4;
		},

		_defaultHorizontalAlignment: "start",

		_defaultVerticalAlignment: "start",

		_defaultRowAlignment: "center"

	});

});
<|endoftext|>


<commit_before>'use strict';

const ini = require('ini');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');

class AwsCredentials {
  save(credentials, profile, done) {
    this.saveAsIniFile(credentials, profile, done);
  }

  saveAsIniFile(credentials, profile, done) {
    const home = AwsCredentials.resolveHomePath();
    const configFile = path.join(home, '.aws', 'credentials');

    if (!credentials) {
      return done(new Error('Invalid AWS credentials'));
    }

    if (!profile) {
      return done(new Error('Cannot save AWS credentials, profile not set'));
    }

    if (!home) {
      return done(new Error('Cannot save AWS credentials, HOME path not set'));
    }

    // mkdirp is a no-op if the directory already exists
    mkdirp(path.join(home, '.aws'), '0700', (mkDirErr) => {
      if (mkDirErr) {
        return done(mkDirErr);
      }

      fs.readFile(configFile, 'utf8', (fsErr, data) => {
        if (fsErr && fsErr.code !== 'ENOENT') {
          return done(fsErr);
        }

        let config = Object.create(null);

        if (data && data !== '') {
          config = ini.parse(data);
        }

        config[profile] = {};
        config[profile].aws_access_key_id = credentials.AccessKeyId;
        config[profile].aws_secret_access_key = credentials.SecretAccessKey;

        // Some libraries e.g. boto v2.38.0, expect an "aws_security_token" entry.
        config[profile].aws_security_token = credentials.SessionToken;
        config = ini.encode(config, {whitespace: true});

        fs.writeFile(configFile, config, 'utf8', done);
      });
    });
  }

  static resolveHomePath() {
    const env = process.env;

    return env.HOME ||
        env.USERPROFILE ||
        (env.HOMEPATH ? ((env.HOMEDRIVE || 'C:/') + env.HOMEPATH) : null);
  }
}

module.exports = AwsCredentials;
<commit_msg>Added aws_session_token back.<commit_after>'use strict';

const ini = require('ini');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');

class AwsCredentials {
  save(credentials, profile, done) {
    this.saveAsIniFile(credentials, profile, done);
  }

  saveAsIniFile(credentials, profile, done) {
    const home = AwsCredentials.resolveHomePath();
    const configFile = path.join(home, '.aws', 'credentials');

    if (!credentials) {
      return done(new Error('Invalid AWS credentials'));
    }

    if (!profile) {
      return done(new Error('Cannot save AWS credentials, profile not set'));
    }

    if (!home) {
      return done(new Error('Cannot save AWS credentials, HOME path not set'));
    }

    // mkdirp is a no-op if the directory already exists
    mkdirp(path.join(home, '.aws'), '0700', (mkDirErr) => {
      if (mkDirErr) {
        return done(mkDirErr);
      }

      fs.readFile(configFile, 'utf8', (fsErr, data) => {
        if (fsErr && fsErr.code !== 'ENOENT') {
          return done(fsErr);
        }

        let config = Object.create(null);

        if (data && data !== '') {
          config = ini.parse(data);
        }

        config[profile] = {};
        config[profile].aws_access_key_id = credentials.AccessKeyId;
        config[profile].aws_secret_access_key = credentials.SecretAccessKey;
        config[profile].aws_session_token = credentials.SessionToken;

        // Some libraries e.g. boto v2.38.0, expect an "aws_security_token" entry.
        config[profile].aws_security_token = credentials.SessionToken;
        config = ini.encode(config, {whitespace: true});

        fs.writeFile(configFile, config, 'utf8', done);
      });
    });
  }

  static resolveHomePath() {
    const env = process.env;

    return env.HOME ||
        env.USERPROFILE ||
        (env.HOMEPATH ? ((env.HOMEDRIVE || 'C:/') + env.HOMEPATH) : null);
  }
}

module.exports = AwsCredentials;
<|endoftext|>


<commit_before>angular.module('cardcast.new', [
  'ngSanitize'
])

.controller('NewCtrl', function($scope, $sanitize, $http, $location, Service) {

  $scope.createCard = function() {

    var cardInfo = {
      title: $scope.title,
      card: $scope.message,
      user: 'user'
    };

    Service.createCard(cardInfo)
      .then(function(resp) {
        $location.path('/cards');
      });

  };

  $scope.changes = function() {
<<<<<<< HEAD
    $scope.preview = $sanitize(Service.markDownCompile($scope.message));
=======
    $scope.preview = $sanitize(Markdown.compile($scope.message));
>>>>>>> 0b05789f1d4e446089325fe928a1e99c9cbac707
  };

});<commit_msg>Resolved conflicts<commit_after>angular.module('cardcast.new', [
  'ngSanitize'
])

.controller('NewCtrl', function($scope, $sanitize, $http, $location, Service) {

  $scope.createCard = function() {

    var cardInfo = {
      title: $scope.title,
      card: $scope.message,
      user: 'user'
    };

    Service.createCard(cardInfo)
      .then(function(resp) {
        $location.path('/cards');
      });

  };

  $scope.changes = function() {
    $scope.preview = $sanitize(Service.markDownCompile($scope.message));
  };

});<|endoftext|>


<commit_before>function isMonad(value) {
	return value && value.isMonad;
}

module.exports = function Monad(bind) {
	return function Unit(value) {
		return isMonad(value) ? value : {
			isMonad: true,
			toString: null,
			bind: function(a, b) { return bind(value, a, b); },
			valueOf: function() { return value; }
		};
	};
};
<commit_msg>spatial<commit_after>function isMonad(value) {
	return value && value.isMonad;
}

module.exports = function SpatialMonad(bind) {
	return function Unit(value) {
		return isMonad(value) ? value : {
			isMonad: true,
			toString: null,
			bind: function(a, b) { return bind(value, a, b); },
			valueOf: function() { return value; }
		};
	};
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';
import OsfModel from './osf-model';

import FileItemMixin from 'ember-osf/mixins/file-item';

/**
 * @module ember-osf
 * @submodule models
 */

/**
 * Model for OSF APIv2 nodes. This model may be used with one of several API endpoints. It may be queried directly,
 *  or accessed via relationship fields.
 * For field and usage information, see:
 * * https://api.osf.io/v2/docs/#!/v2/Node_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Detail_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Children_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Linked_Nodes_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Forks_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/User_Nodes_GET
 * @class Node
 */
export default OsfModel.extend(FileItemMixin, {
    isNode: true,

    title: DS.attr('fixstring'),
    description: DS.attr('fixstring'),
    category: DS.attr('fixstring'),

    // List of strings
    currentUserPermissions: DS.attr(),

    fork: DS.attr('boolean'),
    collection: DS.attr('boolean'),
    registration: DS.attr('boolean'),
    public: DS.attr('boolean'),

    dateCreated: DS.attr('date'),
    dateModified: DS.attr('date'),

    forkedDate: DS.attr('date'),

    nodeLicense: DS.attr(),
    tags: DS.attr(),

    templateFrom: DS.attr('fixstring'),

    parent: DS.belongsTo('node', {
        inverse: 'children'
    }),
    children: DS.hasMany('nodes', {
        inverse: 'parent'
    }),
    preprints: DS.hasMany('preprints', {
        inverse: 'node'
    }),
    affiliatedInstitutions: DS.hasMany('institutions', {
        inverse: 'nodes'
    }),
    comments: DS.hasMany('comments'),
    contributors: DS.hasMany('contributors', {
        allowBulkUpdate: true,
        allowBulkRemove: true,
        inverse: 'node'
    }),
    citation: DS.belongsTo('citation'),

    license: DS.belongsTo('license', {
        inverse: null
    }),

    files: DS.hasMany('file-provider'),
    //forkedFrom: DS.belongsTo('node'),
    linkedNodes: DS.hasMany('nodes', {
        inverse: null,
        serializerType: 'linked-node'
    }),
    registrations: DS.hasMany('registrations', {
        inverse: 'registeredFrom'
    }),

    draftRegistrations: DS.hasMany('draft-registrations', {
        inverse: 'branchedFrom'
    }),

    forks: DS.hasMany('nodes', {
        inverse: 'forkedFrom'
    }),

    forkedFrom: DS.belongsTo('node', {
        inverse: 'forks'
    }),

    root: DS.belongsTo('node', {
        inverse: null
    }),

    wikis: DS.hasMany('wikis', {
        inverse: 'node'
    }),

    logs: DS.hasMany('logs'),

    // These are only computeds because maintaining separate flag values on different classes would be a headache TODO: Improve.
    /**
     * Is this a project? Flag can be used to provide template-specific behavior for different resource types.
     * @property isProject
     * @type boolean
     */
    isProject: Ember.computed.equal('constructor.modelName', 'node'),
    /**
     * Is this a registration? Flag can be used to provide template-specific behavior for different resource types.
     * @property isRegistration
     * @type boolean
     */
    isRegistration: Ember.computed.equal('constructor.modelName', 'registration'),

    /**
     * Is this node being viewed through an anonymized, view-only link?
     * @property isAnonymous
     * @type boolean
     */
    isAnonymous: Ember.computed.bool('meta.anonymous'),

    /**
     * Determine whether the specified user ID is a contributor on this node
     * @method isContributor
     * @param {String} userId
     * @return {boolean} Whether the specified user is a contributor on this node
     */
    isContributor(userId) {
        // Return true if there is at least one matching contributor for this user ID
        if (!userId) {
            return new Ember.RSVP.Promise((resolve) => resolve(false));
        }
        var contribId = `${this.get('id')}-${userId}`;
        return this.store.findRecord('contributor', contribId).then(() => true, () => false);
    },

    save() {
        // Some duplicate logic from osf-model#save needed to support
        // contributor edits being saved through the node
        // Note: order is important here so _dirtyRelationships gets set by the _super call
        var promise = this._super(...arguments);
        if (!this.get('_dirtyRelationships.contributors')) {
            this.set('_dirtyRelationships.contributors', {});
        }

        var contributors = this.hasMany('contributors').hasManyRelationship;
        this.set(
            '_dirtyRelationships.contributors.update',
            contributors.members.list.filter(m => !m.getRecord().get('isNew') && Object.keys(m.getRecord().changedAttributes()).length > 0)
        );
        // Need to included created contributors even in relationship
        // hasLoaded is false
        this.set(
            '_dirtyRelationships.contributors.create',
            contributors.members.list.filter(m => m.getRecord().get('isNew'))
        );
        // Contributors are a 'real' delete, not just a de-reference
        this.set(
            '_dirtyRelationships.contributors.delete',
            this.get('_dirtyRelationships.contributors.remove') || []
        );
        this.set('_dirtyRelationships.contributors.remove', []);
        return promise;
    },

    addChild(title, description=null, category='project', isPublic=false) {
        let child = this.store.createRecord('node', {
            title,
            category,
            description,
            parent: this,
            public: isPublic
        });

        return child.save();
    },

    addContributor(userId, permission, isBibliographic, sendEmail, fullName, email) {
        let contrib = this.store.createRecord('contributor', {
            permission: permission,
            bibliographic: isBibliographic,
            sendEmail: sendEmail,
            nodeId: this.get('id'),
            userId: userId,
            fullName: fullName,
            email: email
        });

        return contrib.save();
    },

    addContributors(contributors, sendEmail) {
        let payload = contributors.map(contrib => {
            let c = this.store.createRecord('contributor', {
                permission: contrib.permission,
                bibliographic: contrib.bibliographic,
                nodeId: this.get('id'),
                userId: contrib.userId,
                id: this.get('id') + '-' + contrib.userId,
                unregisteredContributor: null
            });
            return c.serialize({
                includeId: true,
                includeUser: true
            }).data;
        });

        let emailQuery = '';
        if (!sendEmail) {
            emailQuery = '?send_email=false';
        } else if (sendEmail === 'preprint') {
            emailQuery = '?send_email=preprint';
        }

        // TODO Get this working properly - should not be an ajax request in the future.
        return this.store.adapterFor('contributor').ajax(this.get('links.relationships.contributors.links.related.href') + emailQuery, 'POST', {
            data: {
                data: payload
            },
            isBulk: true
        }).then(resp => {
            this.store.pushPayload(resp);
            var createdContribs = Ember.A();
            resp.data.map((contrib) => {
                createdContribs.push(this.store.peekRecord('contributor', contrib.id));
            });
            return createdContribs;
        });
    },

    removeContributor(contributor) {
        return contributor.destroyRecord();
    },

    updateContributor(contributor, permissions, bibliographic) {
        if (!Ember.isEmpty(permissions))
            contributor.set('permission', permissions);
        if (!Ember.isEmpty(bibliographic))
            contributor.set('bibliographic', bibliographic);
        return contributor.save();
    },

    updateContributors(contributors, permissionsChanges, bibliographicChanges) {
        let payload = contributors
            .filter(contrib => contrib.id in permissionsChanges || contrib.id in bibliographicChanges)
            .map(contrib => {
                if (contrib.id in permissionsChanges) {
                    contrib.set('permission', permissionsChanges[contrib.id]);
                }

                if (contrib.id in bibliographicChanges) {
                    contrib.set('bibliographic', bibliographicChanges[contrib.id]);
                }

                return contrib.serialize({
                    includeId: true,
                    includeUser: false
                }).data;
            });

        return this.store.adapterFor('contributor').ajax(this.get('links.relationships.contributors.links.related.href'), 'PATCH', {
            data: {
                data: payload
            },
            isBulk: true
        }).then(resp => {
            this.store.pushPayload(resp);
            return contributors;
        });
    }
});
<commit_msg>Remove isPublic default value<commit_after>import Ember from 'ember';
import DS from 'ember-data';
import OsfModel from './osf-model';

import FileItemMixin from 'ember-osf/mixins/file-item';

/**
 * @module ember-osf
 * @submodule models
 */

/**
 * Model for OSF APIv2 nodes. This model may be used with one of several API endpoints. It may be queried directly,
 *  or accessed via relationship fields.
 * For field and usage information, see:
 * * https://api.osf.io/v2/docs/#!/v2/Node_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Detail_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Children_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Linked_Nodes_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/Node_Forks_List_GET
 * * https://api.osf.io/v2/docs/#!/v2/User_Nodes_GET
 * @class Node
 */
export default OsfModel.extend(FileItemMixin, {
    isNode: true,

    title: DS.attr('fixstring'),
    description: DS.attr('fixstring'),
    category: DS.attr('fixstring'),

    // List of strings
    currentUserPermissions: DS.attr(),

    fork: DS.attr('boolean'),
    collection: DS.attr('boolean'),
    registration: DS.attr('boolean'),
    public: DS.attr('boolean'),

    dateCreated: DS.attr('date'),
    dateModified: DS.attr('date'),

    forkedDate: DS.attr('date'),

    nodeLicense: DS.attr(),
    tags: DS.attr(),

    templateFrom: DS.attr('fixstring'),

    parent: DS.belongsTo('node', {
        inverse: 'children'
    }),
    children: DS.hasMany('nodes', {
        inverse: 'parent'
    }),
    preprints: DS.hasMany('preprints', {
        inverse: 'node'
    }),
    affiliatedInstitutions: DS.hasMany('institutions', {
        inverse: 'nodes'
    }),
    comments: DS.hasMany('comments'),
    contributors: DS.hasMany('contributors', {
        allowBulkUpdate: true,
        allowBulkRemove: true,
        inverse: 'node'
    }),
    citation: DS.belongsTo('citation'),

    license: DS.belongsTo('license', {
        inverse: null
    }),

    files: DS.hasMany('file-provider'),
    //forkedFrom: DS.belongsTo('node'),
    linkedNodes: DS.hasMany('nodes', {
        inverse: null,
        serializerType: 'linked-node'
    }),
    registrations: DS.hasMany('registrations', {
        inverse: 'registeredFrom'
    }),

    draftRegistrations: DS.hasMany('draft-registrations', {
        inverse: 'branchedFrom'
    }),

    forks: DS.hasMany('nodes', {
        inverse: 'forkedFrom'
    }),

    forkedFrom: DS.belongsTo('node', {
        inverse: 'forks'
    }),

    root: DS.belongsTo('node', {
        inverse: null
    }),

    wikis: DS.hasMany('wikis', {
        inverse: 'node'
    }),

    logs: DS.hasMany('logs'),

    // These are only computeds because maintaining separate flag values on different classes would be a headache TODO: Improve.
    /**
     * Is this a project? Flag can be used to provide template-specific behavior for different resource types.
     * @property isProject
     * @type boolean
     */
    isProject: Ember.computed.equal('constructor.modelName', 'node'),
    /**
     * Is this a registration? Flag can be used to provide template-specific behavior for different resource types.
     * @property isRegistration
     * @type boolean
     */
    isRegistration: Ember.computed.equal('constructor.modelName', 'registration'),

    /**
     * Is this node being viewed through an anonymized, view-only link?
     * @property isAnonymous
     * @type boolean
     */
    isAnonymous: Ember.computed.bool('meta.anonymous'),

    /**
     * Determine whether the specified user ID is a contributor on this node
     * @method isContributor
     * @param {String} userId
     * @return {boolean} Whether the specified user is a contributor on this node
     */
    isContributor(userId) {
        // Return true if there is at least one matching contributor for this user ID
        if (!userId) {
            return new Ember.RSVP.Promise((resolve) => resolve(false));
        }
        var contribId = `${this.get('id')}-${userId}`;
        return this.store.findRecord('contributor', contribId).then(() => true, () => false);
    },

    save() {
        // Some duplicate logic from osf-model#save needed to support
        // contributor edits being saved through the node
        // Note: order is important here so _dirtyRelationships gets set by the _super call
        var promise = this._super(...arguments);
        if (!this.get('_dirtyRelationships.contributors')) {
            this.set('_dirtyRelationships.contributors', {});
        }

        var contributors = this.hasMany('contributors').hasManyRelationship;
        this.set(
            '_dirtyRelationships.contributors.update',
            contributors.members.list.filter(m => !m.getRecord().get('isNew') && Object.keys(m.getRecord().changedAttributes()).length > 0)
        );
        // Need to included created contributors even in relationship
        // hasLoaded is false
        this.set(
            '_dirtyRelationships.contributors.create',
            contributors.members.list.filter(m => m.getRecord().get('isNew'))
        );
        // Contributors are a 'real' delete, not just a de-reference
        this.set(
            '_dirtyRelationships.contributors.delete',
            this.get('_dirtyRelationships.contributors.remove') || []
        );
        this.set('_dirtyRelationships.contributors.remove', []);
        return promise;
    },

    addChild(title, description=null, category='project', isPublic) {
        let child = this.store.createRecord('node', {
            title,
            category,
            description,
            parent: this,
            public: isPublic
        });

        return child.save();
    },

    addContributor(userId, permission, isBibliographic, sendEmail, fullName, email) {
        let contrib = this.store.createRecord('contributor', {
            permission: permission,
            bibliographic: isBibliographic,
            sendEmail: sendEmail,
            nodeId: this.get('id'),
            userId: userId,
            fullName: fullName,
            email: email
        });

        return contrib.save();
    },

    addContributors(contributors, sendEmail) {
        let payload = contributors.map(contrib => {
            let c = this.store.createRecord('contributor', {
                permission: contrib.permission,
                bibliographic: contrib.bibliographic,
                nodeId: this.get('id'),
                userId: contrib.userId,
                id: this.get('id') + '-' + contrib.userId,
                unregisteredContributor: null
            });
            return c.serialize({
                includeId: true,
                includeUser: true
            }).data;
        });

        let emailQuery = '';
        if (!sendEmail) {
            emailQuery = '?send_email=false';
        } else if (sendEmail === 'preprint') {
            emailQuery = '?send_email=preprint';
        }

        // TODO Get this working properly - should not be an ajax request in the future.
        return this.store.adapterFor('contributor').ajax(this.get('links.relationships.contributors.links.related.href') + emailQuery, 'POST', {
            data: {
                data: payload
            },
            isBulk: true
        }).then(resp => {
            this.store.pushPayload(resp);
            var createdContribs = Ember.A();
            resp.data.map((contrib) => {
                createdContribs.push(this.store.peekRecord('contributor', contrib.id));
            });
            return createdContribs;
        });
    },

    removeContributor(contributor) {
        return contributor.destroyRecord();
    },

    updateContributor(contributor, permissions, bibliographic) {
        if (!Ember.isEmpty(permissions))
            contributor.set('permission', permissions);
        if (!Ember.isEmpty(bibliographic))
            contributor.set('bibliographic', bibliographic);
        return contributor.save();
    },

    updateContributors(contributors, permissionsChanges, bibliographicChanges) {
        let payload = contributors
            .filter(contrib => contrib.id in permissionsChanges || contrib.id in bibliographicChanges)
            .map(contrib => {
                if (contrib.id in permissionsChanges) {
                    contrib.set('permission', permissionsChanges[contrib.id]);
                }

                if (contrib.id in bibliographicChanges) {
                    contrib.set('bibliographic', bibliographicChanges[contrib.id]);
                }

                return contrib.serialize({
                    includeId: true,
                    includeUser: false
                }).data;
            });

        return this.store.adapterFor('contributor').ajax(this.get('links.relationships.contributors.links.related.href'), 'PATCH', {
            data: {
                data: payload
            },
            isBulk: true
        }).then(resp => {
            this.store.pushPayload(resp);
            return contributors;
        });
    }
});
<|endoftext|>


<commit_before>import ClickOutsideComponent from '../mixins/click-outside-component';
import Ember from 'ember';

export default Ember.Component.extend(ClickOutsideComponent, {

    /** Setup component css classes. */
    classNames: ['dwcm-autocomplete-textfield'],

    /** Required store. */
    store: null,

    /** Name of the store to fetch data from. */
    storeName: null,

    /** Value of the input field */
    value: '',

    /** Data to display in preview dropdown. */
    previewData: [],

    /** Does the input field have focus. */
    hasFocus: false,

    /** Field to use in autocomplete search */
    filterField: null,

    /** Return if preview dropdown is visible. */
    isDropdownVisible: Ember.computed('previewData', 'hasFocus', function () {
        return this.get('hasFocus') && (
            this.get('previewData').length || this.get('value').length
        );
    }),

    /**
     * Fetch data from server based on search value and update store.
     */
    fetchData () {
        var queryParams = {
            search: true,
            limit: 7,
            orderby: this.get('filterField')
        };

        queryParams[this.get('filterField')] = this.get('value');

        this.store.query(this.storeName, queryParams).then((response) => {
            this.set('previewData', response);
        });
    },

    /** Handle event when user clicks outside of component. */
    onOutsideClick () {
        this.set('hasFocus', false);
    },

    /**
     * Handle keyup events in input field.
     */
    _onKeyup () {
        if (!this.get('value').length) {
            this.set('previewData', []);
        } else {
            this.fetchData();
        }
    },

    actions: {
        /**
        * Handle keyup events in input field.
        *
        * Triggers private method to be able to delay execution.
        *
        */
        onKeyup () {
            // Debounce keyup event if user types fast.
            Ember.run.debounce(this, this._onKeyup, 200);
        },

        /**
         * Handle focus events from input field.
         */
        onFocus () {
            this.set('hasFocus', true);
        },

        /**
         * Handle blur events from input field.
         */
        onBlur () {
            // Don't close when blurred.
            // this.set('hasFocus', false);
        },

        /**
         * Handle click event in dropdown list.
         */
        onItemClick (item) {
            this.set('hasFocus', false);
            this.set(
                'value', item.get(this.get('displayField', 'name'))
            );

            // Should be set from parent.
            this.get('itemSelected')(item);
        }
    }
});
<commit_msg>Handle failed response from server in autocomplete field<commit_after>import ClickOutsideComponent from '../mixins/click-outside-component';
import Ember from 'ember';

export default Ember.Component.extend(ClickOutsideComponent, {

    /** Setup component css classes. */
    classNames: ['dwcm-autocomplete-textfield'],

    /** Required store. */
    store: null,

    /** Name of the store to fetch data from. */
    storeName: null,

    /** Value of the input field */
    value: '',

    /** Data to display in preview dropdown. */
    previewData: [],

    /** Does the input field have focus. */
    hasFocus: false,

    /** Field to use in autocomplete search */
    filterField: null,

    /** Return if preview dropdown is visible. */
    isDropdownVisible: Ember.computed('previewData', 'hasFocus', function () {
        return this.get('hasFocus') && (
            this.get('previewData').length || this.get('value').length
        );
    }),

    /**
     * Fetch data from server based on search value and update store.
     */
    fetchData () {
        var queryParams = {
            search: true,
            limit: 7,
            orderby: this.get('filterField')
        };

        queryParams[this.get('filterField')] = this.get('value');

        this.store.query(this.storeName, queryParams).then((response) => {
            this.set('previewData', response);
        }).catch((reason) => {
            this.set('previewData', []);

            console.warn('Invalid response from server: ', reason);
        });
    },

    /** Handle event when user clicks outside of component. */
    onOutsideClick () {
        this.set('hasFocus', false);
    },

    /**
     * Handle keyup events in input field.
     */
    _onKeyup () {
        if (!this.get('value').length) {
            this.set('previewData', []);
        } else {
            this.fetchData();
        }
    },

    actions: {
        /**
        * Handle keyup events in input field.
        *
        * Triggers private method to be able to delay execution.
        *
        */
        onKeyup () {
            // Debounce keyup event if user types fast.
            Ember.run.debounce(this, this._onKeyup, 200);
        },

        /**
         * Handle focus events from input field.
         */
        onFocus () {
            this.set('hasFocus', true);
        },

        /**
         * Handle blur events from input field.
         */
        onBlur () {
            // Don't close when blurred.
            // this.set('hasFocus', false);
        },

        /**
         * Handle click event in dropdown list.
         */
        onItemClick (item) {
            this.set('hasFocus', false);
            this.set(
                'value', item.get(this.get('displayField', 'name'))
            );

            // Should be set from parent.
            this.get('itemSelected')(item);
        }
    }
});
<|endoftext|>


<commit_before>const libDir = process.env.LIB_DIR;

const transformIgnorePatterns = [];

// if (libDir !== 'es') {
//   transformIgnorePatterns.push('/node_modules/');
// }

module.exports = {
  preset: 'react-native',
  setupFiles: [
    './tests/setup.js'
  ],
  moduleFileExtensions: [
    'ts',
    'tsx',
    'js',
    'jsx',
    'json',
  ],
  testPathIgnorePatterns: [
    '/node_modules/',
    '_site',
    'site',
  ],
  transform: {
    '\\.tsx?$': './node_modules/antd-demo-jest/ts',
    '\\.js$': './node_modules/babel-jest',
    '\\.png': '<rootDir>/tests/imageStub.js',
  },
  testRegex: libDir === 'dist' ? 'demo\\.test\\.js$' : '.*\\.test\\.js$',
  collectCoverageFrom: [
    'components/**/*.{ts,tsx}',
    '!components/**/demo/*.{ts,tsx}',
    '!components/**/*.web.{ts,tsx}',
    '!components/*/style/index.tsx',
  ],
  transformIgnorePatterns,
};
<commit_msg>Remove commented codes<commit_after>const libDir = process.env.LIB_DIR;

const transformIgnorePatterns = [];

module.exports = {
  preset: 'react-native',
  setupFiles: [
    './tests/setup.js'
  ],
  moduleFileExtensions: [
    'ts',
    'tsx',
    'js',
    'jsx',
    'json',
  ],
  testPathIgnorePatterns: [
    '/node_modules/',
    '_site',
    'site',
  ],
  transform: {
    '\\.tsx?$': './node_modules/antd-demo-jest/ts',
    '\\.js$': './node_modules/babel-jest',
    '\\.png': '<rootDir>/tests/imageStub.js',
  },
  testRegex: libDir === 'dist' ? 'demo\\.test\\.js$' : '.*\\.test\\.js$',
  collectCoverageFrom: [
    'components/**/*.{ts,tsx}',
    '!components/**/demo/*.{ts,tsx}',
    '!components/**/*.web.{ts,tsx}',
    '!components/*/style/index.tsx',
  ],
  transformIgnorePatterns,
};
<|endoftext|>


<commit_before>/**
 * controller
 * @return
 */
module.exports = Controller("Home/BaseController", function(){
  "use strict";
  var Service = require("../../Service/Service");
  var captchapng = require('captchapng');

  return {
    updateAction: function(){
      var self = this;
      if(self.isGet()){
        return self.redirect("/");
      }else if(self.isPost()){
        var user_id = self.post('id');
        var _user_id = self.userInfo.id;
        if (_user_id) {
          if(_user_id == user_id){
            return Service.updateUserById(self.post()).then(function(content){
              if(content == 0){
                return self.success()
              }else if(content == -1){
                throw new Error('没有找到该用户！')
              }
            }).catch(function(err){
              return self.error(err.message || "系统异常，请稍后再试！")
            })
          }else{
            self.session('userInfo', '');
            self.redirect('/');
          }
        }else{
          self.redirect('/');
        }
      }
    },

    logoutAction: function() {
      var self = this;
      if(self.isGet()){
        self.session('userInfo', '');
        self.cookie(AUTH_ID, '',  {
            domain: "",
            path: "/",
            httponly: true,
            timeout: 0
        });
        self.redirect('/');
      }
    },

    signinAction: function(){
      var self = this;
      if(self.isGet()){

      }else if(self.isPost()){
        var data = self.post();
        if(!data.username || !data.password){
          return self.error("请输入正确的用户名和密码")
        }
        Service.createUser(data).then(function(content){
          if(isNumber(content)){
            if(content == -1){
              throw new Error("用户已经存在！")
            }else if(content == -2){
              throw new Error("系统异常，请稍后再试！")
            }else{
              self.session('userInfo',extend({},data,{id:content}))
              return self.success(content);
            }
          }else{
            throw new Error("系统异常，请稍后再试！")
          }
        }).catch(function(err){
          return self.error(err.message || "系统异常，请稍后再试！")
        })
      }
    },

    loginAction: function(){
      var self = this;
      if(self.isGet()){

      }else if(self.isPost()){
        var data = self.post();
        if(!data.username || !data.password){
          return self.err("请输入正确的用户名和密码")
        }
        Service.loginUser(data).then(function(content){
          if(isNumber(content)){
            if(content == -1){
              throw new Error("没有找到该用户！")
            }else if(content == -2){
              throw new Error("用户名或者密码错误！")
            }else{
              Service.getUserById({id : content}).then(function(u_content){
                if(data.remember == 1){
                  self.cookie(AUTH_ID, encrypt(data.username + '\t' + content + u_content[0].avator), {
                      domain: "",
                      path: "/",
                      httponly: true,
                      timeout: 60 * 60 * 24 * 30
                  })
                }
                self.session('userInfo',extend({},data,{id:content,avator : u_content[0].avator}))
                return self.success();
              })

            }
          }else{
            throw new Error("系统异常，请稍后再试！")
          }
        }).catch(function(err){
          self.error(err.message || "系统异常，请稍后再试！");
        })
      }
    },

    checkemailAction: function(){
      var self = this;
      Service.checkEmail({"username" : this.param('username')}).then(function(content){
        if(content == 0){
          return self.success({num : content})
        }else if(content == 1){
          return self.success({num : content , msg : "用户已经存在！"})
        }
      }).catch(function(err){
        self.error(err);
      })
    },

    forgetAction: function(){
      var self = this;
      if(self.isGet()){
        self.assign({
          title : "忘记密码",
          section : 'user',
          link: 'forget',
          userInfo : self.userInfo
        })
        return self.display()
      }else if(self.isPost()){
        var data = self.post();
        self.session('captchacode').then(function(res){
          if(data.verifycode == res){
            Service.sendEmail({
              email: data.email,
              subject : "找回密码",
              link:'forget',
              message : "http://www.nebulafe.com/user/reset/?verify=" + encrypt(data.email)
            })
            return self.success();
          }else{
            self.error("验证码错误！");
          }
        })
      }
    },

    // for the same user
    seeAction: function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getStudyProgress({userid : user_id}).then(function(content){
          console.log(content);
        })
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "查看用户",
            section : 'user',
            link:'see',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    },

    // for the other user
    profileAction : function(){
      var  self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/")
        }
        var value = self.userInfo;
        if(value && value.id == user_id){
          return self.redirect("/user/see/" + user_id)
        }
        Service.getUserById({id : user_id}).then(function(content){
          self.assign({
            title : "查看用户",
            section : 'user',
            link : 'see',
            avator : content[0].avator,
            nickname : content[0].nickname
          })
          return self.display()
        })
      }
    },

    avatorAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "设置头像",
            section : 'user',
            link:'avator',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    },

    verifyemailAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "验证邮箱",
            section : 'user',
            link:'verifyemail',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }else if(self.isPost()){
        var data = self.post();
        self.session('captchacode').then(function(res){
          if(data.verifycode == res){
            Service.sendEmail({
              email: data.email,
              subject : "验证邮箱",
              message : "http://www.nebulafe.com/user/activate/?verify=" + encrypt(data.email)
            })
            return self.success();
          }else{
            self.error("验证码错误！");
          }
        })
      }
    },

    setpwdAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "修改密码",
            section : 'user',
            link:'setpwd',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    },

    resetAction: function(){
      var self = this;
      if(self.isGet()){
        var id = self.get('verify');
        if(!id){
          self.redirect("/")
        }else{
          try{
            var email = decrypt(id);
            if(!isEmail(email)){
              self.redirect("/")
            }
            self.assign({
              title : "重置密码",
              section : 'user',
              link:'reset',
              userInfo : self.userInfo,
              email: email
            });
            self.display()
          }catch(e){
            return self.redirect("/")
          }
        }
      }else if(self.isPost()){
        var data = self.post();
        Service.resetPwd(data).then(function(res){
          self.success(res)
        }).catch(function(e){
          self.error("系统异常，请稍后再试！");
        })
      }
    },

    getcodeAction: function(){
      var self = this;
      var captchacode = parseInt(Math.random()*9000+1000);
      self.session('captchacode', captchacode);
      var p = new captchapng(70,38,captchacode);
      p.color(0, 12, 0, 0);
      p.color(80, 80, 200, 255);

      var img = p.getBase64();
      var imgbase64 = new Buffer(img,'base64');
      self.header({
          'Content-Type': 'image/png'
      })
      self.end(imgbase64);
    },

    activateAction : function(){
      var self = this;
      if(self.isGet()){
        var id = self.get('verify');
        if(!id){
          self.redirect("/")
        }else{
          try{
            var email = decrypt(id);
            if(!isEmail(email)){
              return self.redirect("/")
            }
            Service.getUserById({"username" : email}).then(function(content){
              if(content && content[0]){
                Service.setUserStatus({
                  "id": content[0].id,
                  "activate_email" : true
                })
                return self.redirect('/')
              }
            })
          }catch(e){
            return self.redirect("/")
          }
        }
      }
    },

    mycourseAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "我的课程",
            section : 'user',
            link:'setpwd',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    }

  };
})
<commit_msg>add files by wangpengfei<commit_after>/**
 * controller
 * @return
 */
module.exports = Controller("Home/BaseController", function(){
  "use strict";
  var Service = require("../../Service/Service");
  var captchapng = require('captchapng');

  return {
    updateAction: function(){
      var self = this;
      if(self.isGet()){
        return self.redirect("/");
      }else if(self.isPost()){
        var user_id = self.post('id');
        var _user_id = self.userInfo.id;
        if (_user_id) {
          if(_user_id == user_id){
            return Service.updateUserById(self.post()).then(function(content){
              if(content == 0){
                return self.success()
              }else if(content == -1){
                throw new Error('没有找到该用户！')
              }
            }).catch(function(err){
              return self.error(err.message || "系统异常，请稍后再试！")
            })
          }else{
            self.session('userInfo', '');
            self.redirect('/');
          }
        }else{
          self.redirect('/');
        }
      }
    },

    logoutAction: function() {
      var self = this;
      if(self.isGet()){
        self.session('userInfo', '');
        self.cookie(AUTH_ID, '',  {
            domain: "",
            path: "/",
            httponly: true,
            timeout: 0
        });
        self.redirect('/');
      }
    },

    signinAction: function(){
      var self = this;
      if(self.isGet()){

      }else if(self.isPost()){
        var data = self.post();
        if(!data.username || !data.password){
          return self.error("请输入正确的用户名和密码")
        }
        Service.createUser(data).then(function(content){
          if(isNumber(content)){
            if(content == -1){
              throw new Error("用户已经存在！")
            }else if(content == -2){
              throw new Error("系统异常，请稍后再试！")
            }else{
              self.session('userInfo',extend({},data,{id:content}))
              return self.success(content);
            }
          }else{
            throw new Error("系统异常，请稍后再试！")
          }
        }).catch(function(err){
          return self.error(err.message || "系统异常，请稍后再试！")
        })
      }
    },

    loginAction: function(){
      var self = this;
      if(self.isGet()){

      }else if(self.isPost()){
        var data = self.post();
        if(!data.username || !data.password){
          return self.err("请输入正确的用户名和密码")
        }
        Service.loginUser(data).then(function(content){
          if(isNumber(content)){
            if(content == -1){
              throw new Error("没有找到该用户！")
            }else if(content == -2){
              throw new Error("用户名或者密码错误！")
            }else{
              Service.getUserById({id : content}).then(function(u_content){
                if(data.remember == 1){
                  self.cookie(AUTH_ID, encrypt(data.username + '\t' + content  + '\t' + u_content[0].avator), {
                      domain: "",
                      path: "/",
                      httponly: true,
                      timeout: 60 * 60 * 24 * 30
                  })
                }
                self.session('userInfo',{id:content,avator : u_content[0].avator,username:u_content[0].username})
                return self.success();
              })

            }
          }else{
            throw new Error("系统异常，请稍后再试！")
          }
        }).catch(function(err){
          self.error(err.message || "系统异常，请稍后再试！");
        })
      }
    },

    checkemailAction: function(){
      var self = this;
      Service.checkEmail({"username" : this.param('username')}).then(function(content){
        if(content == 0){
          return self.success({num : content})
        }else if(content == 1){
          return self.success({num : content , msg : "用户已经存在！"})
        }
      }).catch(function(err){
        self.error(err);
      })
    },

    forgetAction: function(){
      var self = this;
      if(self.isGet()){
        self.assign({
          title : "忘记密码",
          section : 'user',
          link: 'forget',
          userInfo : self.userInfo
        })
        return self.display()
      }else if(self.isPost()){
        var data = self.post();
        self.session('captchacode').then(function(res){
          if(data.verifycode == res){
            Service.sendEmail({
              email: data.email,
              subject : "找回密码",
              link:'forget',
              message : "http://www.nebulafe.com/user/reset/?verify=" + encrypt(data.email)
            })
            return self.success();
          }else{
            self.error("验证码错误！");
          }
        })
      }
    },

    // for the same user
    seeAction: function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getStudyProgress({userid : user_id}).then(function(content){
          console.log(content);
        })
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "查看用户",
            section : 'user',
            link:'see',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    },

    // for the other user
    profileAction : function(){
      var  self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/")
        }
        var value = self.userInfo;
        if(value && value.id == user_id){
          return self.redirect("/user/see/" + user_id)
        }
        Service.getUserById({id : user_id}).then(function(content){
          self.assign({
            title : "查看用户",
            section : 'user',
            link : 'see',
            avator : content[0].avator,
            nickname : content[0].nickname
          })
          return self.display()
        })
      }
    },

    avatorAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "设置头像",
            section : 'user',
            link:'avator',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    },

    verifyemailAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "验证邮箱",
            section : 'user',
            link:'verifyemail',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }else if(self.isPost()){
        var data = self.post();
        self.session('captchacode').then(function(res){
          if(data.verifycode == res){
            Service.sendEmail({
              email: data.email,
              subject : "验证邮箱",
              message : "http://www.nebulafe.com/user/activate/?verify=" + encrypt(data.email)
            })
            return self.success();
          }else{
            self.error("验证码错误！");
          }
        })
      }
    },

    setpwdAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "修改密码",
            section : 'user',
            link:'setpwd',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    },

    resetAction: function(){
      var self = this;
      if(self.isGet()){
        var id = self.get('verify');
        if(!id){
          self.redirect("/")
        }else{
          try{
            var email = decrypt(id);
            if(!isEmail(email)){
              self.redirect("/")
            }
            self.assign({
              title : "重置密码",
              section : 'user',
              link:'reset',
              userInfo : self.userInfo,
              email: email
            });
            self.display()
          }catch(e){
            return self.redirect("/")
          }
        }
      }else if(self.isPost()){
        var data = self.post();
        Service.resetPwd(data).then(function(res){
          self.success(res)
        }).catch(function(e){
          self.error("系统异常，请稍后再试！");
        })
      }
    },

    getcodeAction: function(){
      var self = this;
      var captchacode = parseInt(Math.random()*9000+1000);
      self.session('captchacode', captchacode);
      var p = new captchapng(70,38,captchacode);
      p.color(0, 12, 0, 0);
      p.color(80, 80, 200, 255);

      var img = p.getBase64();
      var imgbase64 = new Buffer(img,'base64');
      self.header({
          'Content-Type': 'image/png'
      })
      self.end(imgbase64);
    },

    activateAction : function(){
      var self = this;
      if(self.isGet()){
        var id = self.get('verify');
        if(!id){
          self.redirect("/")
        }else{
          try{
            var email = decrypt(id);
            if(!isEmail(email)){
              return self.redirect("/")
            }
            Service.getUserById({"username" : email}).then(function(content){
              if(content && content[0]){
                Service.setUserStatus({
                  "id": content[0].id,
                  "activate_email" : true
                })
                return self.redirect('/')
              }
            })
          }catch(e){
            return self.redirect("/")
          }
        }
      }
    },

    mycourseAction : function(){
      var self = this;
      if(self.isGet()){
        var user_id = self.get('id');
        if(!user_id){
          return self.redirect("/");
        }
        var value = self.userInfo;
        Service.getUserById({id:user_id}).then(function(content){
          self.assign({
            title : "我的课程",
            section : 'user',
            link:'setpwd',
            userInfo : content[0]
          })
          return self.display()
        }).catch(function(err){})
      }
    }

  };
})
<|endoftext|>


<commit_before>/* JavaScript for DbFrontend List page
 * Script allows inline editing of the table contents
 * For any DbFrontend page using this javascript, check the following things to make if work properly:
 *  1. That the SiteDefs::OBJECT_TO_SCRIPT values for the page is 'Modal'
 *  2. Javascript classes are being added to the html elements properly
 *  3. The page which displays all the records return a single record if its 'id' is specified in GET params
 */

Ensembl.Panel.DbFrontendList = Ensembl.Panel.extend({

  init: function() {
    var self = this;
    this.base();
    this.data = [];

    $('>table', this.el).each(function() {
      $('th', this.firstChild).each(function() {
        var inps = $('input[type=hidden]', this);
        self.data.push(inps.length ? {url: inps[0].value, name: inps[0].name} : false);
      });
      $('tr', this).each(function () {
        if (this.previousSibling) {
          self.dbfRow(this);
        }
      });
      return false;
    });
  },

  dbfRow: function(row) {
    var id = (row.className.match(/_dbf_row_([^\s]+)/) || []).pop();
    for (var i in this.data) {
      if (this.data[i]) {
        new Ensembl.DbFrontendListCell(row.cells[i], $.extend(this.data[i], {id: id, parent: this}));
      }
    }
  }
});

Ensembl.DbFrontendListCell = Base.extend({
  constructor: function(cell, data) {
    var self   = this;
    $.extend(this, data);

    this.el = $('
').html(cell.innerHTML).appendTo($(cell).empty()).append($('').click(function() {
      if (!self.form) {
        self.createForm();
      }
      self.makeRequest(self.form, {
        url:      self.url,
        data:     {id: self.id, _ajax: 1, _list: 1},
        success:  function(json) {
          var form   = $('form', this.getResponseNode(json));
          var field  = $('[name=' + self.name + ']', form).first().parents('div').first().removeAttr('class');
          var button = $('[type=submit]', form).first().parents('div').first().attr('class', 'dbf-list-buttons');
          this.form.empty().append(form.empty().append(field, $('
').append(button)));
        }
      });
    }));
  },

  createForm: function() {
    var self = this;
    if (this.form) {
      return;
    }
    this.form = $('
').insertAfter(this.el).hide();

    // Cancel button's event
    $('._dbf_cancel', this.form).live('click', function (event) {
      event.preventDefault();
      self.el.show('fast');
      self.form.hide('fast', function() {
        this.innerHTML = '';
      });
    });

    // Submit event of the form for saving the data
    $('form._dbf_save', this.form).live('submit', function(event) {
      event.preventDefault();
      self.makeRequest(self.form, {
        url:     this.action,
        type:    'POST',
        data:    $(this).serialize() + '&id=' + self.id + '&_ajax=1',
        success: function(json) {
          if (json.redirectURL) {
            var url = window.location.href.split('#')[0];
            this.success = !json.redirectURL.match(/Problem$/);
            this.makeRequest(this.form, {
              async: false,
              url: url,
              data: {id: this.id, _ajax: 1},
              success: function(json) {
                if (this.success) {
                  var res = $('._dbf_row_' + this.id, this.getResponseNode(json));
                  if (res.length) {
                    var tr = this.el.parents('tr').first();
                    this.parent.dbfRow(res.attr({'class': tr[0].className}).replaceAll(tr)[0]);
                  }
                }
                this.afterResponse(this.success);
              }
            });
          }
          else {
            this.showError();
          }
        }
      });
    });
  },

  makeRequest: function(target, options) {
    if (this.ajax) {
      this.ajax.abort();
      this.ajax = false;
    }
    this.el.hide();
    target.empty().html('Loading…').show();
    this.ajax = $.ajax($.extend(options, {
      dataType: 'json',
      context: this || options.context,
      error: function() {
        this.showError();
      }
    }));
  },

  getResponseNode: function(json) {
    return $('._dbf_response', $(document.createElement('div')).html(json.content));
  },

  showError: function() {
    this.el.show();
    this.form.html('An error occoured at the server. Please try again.');
  },

  afterResponse: function(success) {}
});<commit_msg>DbFrontendList made compatiable with DataTable<commit_after>/* JavaScript for DbFrontend List page
 * Script allows inline editing of the table contents
 * For any DbFrontend page using this javascript, check the following things to make if work properly:
 *  1. That the SiteDefs::OBJECT_TO_SCRIPT values for the page is 'Modal'
 *  2. Javascript classes are being added to the html elements properly
 *  3. The page which displays all the records return a single record if its 'id' is specified in GET params
 */

Ensembl.Panel.DbFrontendList = Ensembl.Panel.extend({

  init: function() {
    var self = this;
    this.base();
    this.data = [];

    $('table._dbf_list', this.el).each(function() {
      $('thead th', this).each(function() {
        var inps = $('input[type=hidden]', this);
        self.data.push(inps.length ? {url: inps[0].value, name: inps[0].name} : false);
      });
      $('tbody tr', this).each(function () {
        self.dbfRow(this);
      });
      return false;
    });
  },

  dbfRow: function(row) {
    var id = (row.className.match(/_dbf_row_([^\s]+)/) || []).pop();
    for (var i in this.data) {
      if (this.data[i]) {
        new Ensembl.DbFrontendListCell(row.cells[i], $.extend(this.data[i], {id: id, parent: this}));
      }
    }
  }
});

Ensembl.DbFrontendListCell = Base.extend({
  constructor: function(cell, data) {
    var self   = this;
    $.extend(this, data);

    this.el = $('
').html(cell.innerHTML).appendTo($(cell).empty()).append($('').click(function() {
      if (!self.form) {
        self.createForm();
      }
      self.makeRequest(self.form, {
        url:      self.url,
        data:     {id: self.id, _ajax: 1, _list: 1},
        success:  function(json) {
          var form   = $('form', this.getResponseNode(json));
          var field  = $('[name=' + self.name + ']', form).first().parents('div').first().removeAttr('class');
          var button = $('[type=submit]', form).first().parents('div').first().attr('class', 'dbf-list-buttons');
          this.form.empty().append(form.empty().append(field, $('
').append(button)));
        }
      });
    }));
  },

  createForm: function() {
    var self = this;
    if (this.form) {
      return;
    }
    this.form = $('
').insertAfter(this.el).hide();

    // Cancel button's event
    $('._dbf_cancel', this.form).live('click', function (event) {
      event.preventDefault();
      self.el.show('fast');
      self.form.hide('fast', function() {
        this.innerHTML = '';
      });
    });

    // Submit event of the form for saving the data
    $('form._dbf_save', this.form).live('submit', function(event) {
      event.preventDefault();
      self.makeRequest(self.form, {
        url:     this.action,
        type:    'POST',
        data:    $(this).serialize() + '&id=' + self.id + '&_ajax=1',
        success: function(json) {
          if (json.redirectURL) {
            var url = window.location.href.split('#')[0];
            this.success = !json.redirectURL.match(/Problem$/);
            this.makeRequest(this.form, {
              async: false,
              url: url,
              data: {id: this.id, _ajax: 1},
              success: function(json) {
                if (this.success) {
                  var res = $('._dbf_row_' + this.id, this.getResponseNode(json));
                  if (res.length) {
                    var row = this.el.parents('tr').first();
                    var td  = $('td', res);
                    $('td', row).each(function(i) {
                      this.innerHTML = td[i].innerHTML;
                    });
                    var table = row.parents('table').first();
                    if (table.hasClass('data_table')) {
                      table.dataTable().fnUpdate(($.map(row[0].cells, function(cell) {return cell.innerHTML; })), row[0]);
                    }
                    this.parent.dbfRow(row[0]);
                  }
                }
                this.afterResponse(this.success);
              }
            });
          }
          else {
            this.showError();
          }
        }
      });
    });
  },

  makeRequest: function(target, options) {
    if (this.ajax) {
      this.ajax.abort();
      this.ajax = false;
    }
    this.el.hide();
    target.empty().html('Loading…').show();
    this.ajax = $.ajax($.extend(options, {
      dataType: 'json',
      context: this || options.context,
      error: function() {
        this.showError();
      }
    }));
  },

  getResponseNode: function(json) {
    return $('._dbf_response', $(document.createElement('div')).html(json.content));
  },

  showError: function() {
    this.el.show();
    this.form.html('An error occoured at the server. Please try again.');
  },

  afterResponse: function(success) {}
});<|endoftext|>