<commit_before>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

/**
 * Internal dependencies
 */
import Snackbar from './snackbar';

function getLeft(position) {
  switch (position) {
    case 'top':
    case 'bottom':
      return 'calc(50% - 10em)';
    case 'top-left':
    case 'bottom-left':
      return '60px';
    case 'top-right':
    case 'bottom-right':
      return 'calc(100vw - 20.5em)';
    default:
      return '60px';
  }
}

const Container = styled.div`
  position: fixed;
  top: ${({ position }) => (position.indexOf('top') === 0 ? 0 : 'inherit')};
  bottom: ${({ position }) =>
    position.indexOf('bottom') === 0 ? 0 : 'inherit'};
  left: ${({ position }) => getLeft(position)};
  z-index: 10000;
`;

const ChildContainer = styled.div`
  &.react-snackbar-alert__snackbar-container-enter {
    opacity: 0;
    transform: scaleY(0.1);
  }

  &.react-snackbar-alert__snackbar-container-enter-active {
    opacity: 1;
    transform: scaleY(1);
    transition: all ${({ animationTimeout }) => animationTimeout}ms;
  }

  &.react-snackbar-alert__snackbar-container-exit {
    opacity; 1;
    transform: scaleY(1);
  }

  &.react-snackbar-alert__snackbar-container-exit-active {
    opacity: 0;
    transform: scaleY(0.1);
    transition: all ${({ animationTimeout }) => animationTimeout}ms;
  }
`;

function SnackbarContainer({
  component: Component,
  notifications,
  onRemove,
  position,
  animationTimeout,
}) {
  const orderednotifications =
    position.indexOf('top') === 0
      ? [...notifications].reverse()
      : notifications;
  return (
    <Container position={position}>
      <TransitionGroup>
        {orderednotifications.map((notification) => (
          <CSSTransition
            in
            appear={true}
            key={notification.key}
            timeout={notification.animationTimeout || animationTimeout}
            classNames="react-snackbar-alert__snackbar-container"
          >
            <ChildContainer
              animationTimeout={
                notification.animationTimeout || animationTimeout
              }
            >
              <Component
                timeout={notification.timeout}
                onDismiss={() => onRemove(notification)}
                notification={notification}
                data={notification.data}
                position={position}
              />
            </ChildContainer>
          </CSSTransition>
        ))}
      </TransitionGroup>
    </Container>
  );
}

SnackbarContainer.propTypes = {
  animationTimeout: PropTypes.number,
  component: PropTypes.elementType,
  notifications: PropTypes.array,
  onRemove: PropTypes.func.isRequired,
  position: PropTypes.oneOf([
    'top',
    'bottom',
    'top-left',
    'top-right',
    'bottom-left',
    'bottom-right',
  ]),
};

SnackbarContainer.defaultProps = {
  component: Snackbar,
  position: 'bottom',
  animationTimeout: 250,
};

export default SnackbarContainer;
<commit_msg>fix lint issue<commit_after>/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

/**
 * Internal dependencies
 */
import Snackbar from './snackbar';

function getLeft(position) {
  switch (position) {
    case 'top':
    case 'bottom':
      return 'calc(50% - 10em)';
    case 'top-left':
    case 'bottom-left':
      return '60px';
    case 'top-right':
    case 'bottom-right':
      return 'calc(100vw - 20.5em)';
    default:
      return '60px';
  }
}

const Container = styled.div`
  position: fixed;
  top: ${({ position }) => (position.indexOf('top') === 0 ? 0 : 'inherit')};
  bottom: ${({ position }) =>
    position.indexOf('bottom') === 0 ? 0 : 'inherit'};
  left: ${({ position }) => getLeft(position)};
  z-index: 10000;
`;

const ChildContainer = styled.div`
  &.react-snackbar-alert__snackbar-container-enter {
    opacity: 0;
    transform: scaleY(0.1);
  }

  &.react-snackbar-alert__snackbar-container-enter-active {
    opacity: 1;
    transform: scaleY(1);
    transition: all ${({ animationTimeout }) => animationTimeout}ms;
  }

  &.react-snackbar-alert__snackbar-container-exit {
    opacity: 1;
    transform: scaleY(1);
  }

  &.react-snackbar-alert__snackbar-container-exit-active {
    opacity: 0;
    transform: scaleY(0.1);
    transition: all ${({ animationTimeout }) => animationTimeout}ms;
  }
`;

function SnackbarContainer({
  component: Component,
  notifications,
  onRemove,
  position,
  animationTimeout,
}) {
  const orderednotifications =
    position.indexOf('top') === 0
      ? [...notifications].reverse()
      : notifications;
  return (
    <Container position={position}>
      <TransitionGroup>
        {orderednotifications.map((notification) => (
          <CSSTransition
            in
            appear={true}
            key={notification.key}
            timeout={notification.animationTimeout || animationTimeout}
            classNames="react-snackbar-alert__snackbar-container"
          >
            <ChildContainer
              animationTimeout={
                notification.animationTimeout || animationTimeout
              }
            >
              <Component
                timeout={notification.timeout}
                onDismiss={() => onRemove(notification)}
                notification={notification}
                data={notification.data}
                position={position}
              />
            </ChildContainer>
          </CSSTransition>
        ))}
      </TransitionGroup>
    </Container>
  );
}

SnackbarContainer.propTypes = {
  animationTimeout: PropTypes.number,
  component: PropTypes.elementType,
  notifications: PropTypes.array,
  onRemove: PropTypes.func.isRequired,
  position: PropTypes.oneOf([
    'top',
    'bottom',
    'top-left',
    'top-right',
    'bottom-left',
    'bottom-right',
  ]),
};

SnackbarContainer.defaultProps = {
  component: Snackbar,
  position: 'bottom',
  animationTimeout: 250,
};

export default SnackbarContainer;
<|endoftext|>


<commit_before>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2015 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function() {

"use strict";

var ui = angular.module('axelor.ui');

var BLANK = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
var META_FILE = "com.axelor.meta.db.MetaFile";

ui.makeImageURL = function makeURL(model, field, recordOrId) {
	var value = recordOrId;
	if (!value) return null;
	var id = value.id ? value.id : value;
	var version = value.version || value.$version || (new Date()).getTime();
	if (!id || id <= 0) return null;
	return "ws/rest/" + model + "/" + id + "/" + field + "/download?v=" + version;
};

ui.formInput('ImageLink', {
	css: 'image-item',
	cssClass: 'from-item image-item',

	controller: ['$scope', '$element', '$interpolate', function($scope, $element, $interpolate) {

		$scope.parseText = function(text) {
			if (!text) return BLANK;
			if (!text.match(/{{.*?}}/)) {
				return text;
			}
			return $interpolate(text)($scope.record);
		};
	}],

	init: function(scope) {
		var field = scope.field;

		var width = field.width || 140;
		var height = field.height || '100%';

		scope.styles = [{
			'width': width,
			'max-width': '100%',
			'max-height': '100%'
		}, {
			'width': width,
			'height': height,
			'max-width': '100%',
			'max-height': '100%'
		}];

		if (field.noframe) {
			_.extend(scope.styles[1], {
				border: 0,
				padding: 0,
				background: 'none',
				boxShadow: 'none'
			});
		}
	},

	link_readonly: function(scope, element, attrs, model) {

		var image = element.children('img:first');

		scope.$render_readonly = function() {
			image.get(0).src = scope.parseText(model.$viewValue) || BLANK;
		};

		scope.$watch("record.id", function(id, old) {
			if (scope.isReadonly()) {
				scope.$render_readonly();
			}
		});
	},
	template_editable: '<input type="text">',
	template_readonly:
		'
'+
			''+
		'
'
});

ui.formInput('Image', 'ImageLink', {

	init: function(scope) {
		this._super.apply(this, arguments);

		var field = scope.field;
		var isBinary = field.serverType === 'binary';

		if (!isBinary && field.target !== META_FILE) {
			throw new Error("Invalid field type for Image widget.");
		}

		scope.parseText = function (value) {
			return scope.getLink(value);
		};

		scope.getLink = function (value) {
			var record = scope.record || {};
			var model = scope._model;
			if (!record.id || value === null) return value || BLANK;
			if (isBinary) {
				if (value) return value;
				return makeURL(model, field.name, record) + "&image=true";
			}
			return makeURL(META_FILE, "content", (value.id || value));
		};
	},

	link_editable: function(scope, element, attrs, model) {

		var field = scope.field;
		var input = element.children('input:first');
		var image = element.children('img:first');
		var buttons = element.children('.btn-group');

		var isBinary = field.serverType === 'binary';
		var timer = null;

		input.add(buttons).hide();
		element.on('mouseenter', function (e) {
			if (timer) clearTimeout(timer);
			timer = setTimeout(function () {
				buttons.slideDown();
			}, 500);
		});
		element.on('mouseleave', function (e) {
			if (timer) {
				clearTimeout(timer);
				timer = null;
			}
			buttons.slideUp();
		});

		scope.doSelect = function() {
			input.click();
		};

		scope.doSave = function() {
			var content = image.get(0).src;
			if (content) {
				window.open(content);
			}
		};

		scope.doRemove = function() {
			image.get(0).src = "";
			input.val(null);
			update(null);
		};

		input.change(function(e, ui) {
			var file = input.get(0).files[0];
			var uploadSize = axelor.config["file.upload.size"];

			// reset file selection
			input.get(0).value = null;

			if (!file) {
				return;
			}

			if(file.size > 1048576 * parseInt(uploadSize)) {
				return axelor.dialogs.say(_t("You are not allow to upload a file bigger than") + ' ' + uploadSize + 'MB');
			}

			if (!isBinary) {
				return doUpload(file);
			}

			var reader = new FileReader();
			reader.onload = function(e) {
				update(e.target.result, file.name);
			};

			reader.readAsDataURL(file);
		});

		function doUpload(file) {
			var ds = scope._dataSource._new(META_FILE);
			var value = field.target === META_FILE ? (scope.getValue()||{}) : {};
			var record = {
				fileName: file.name,
				fileType: file.type,
				fileSize: file.size,
				id: value.id,
				version: value.version || value.$version
		    };

			record.$upload = {
			    file: file
		    };

			ds.save(record).success(function (saved) {
				update(saved);
			});
		}

		function doUpdate(value) {
			image.get(0).src = scope.getLink(value);
			model.$setViewValue(getData(value));
		}

		function update(value) {
			scope.applyLater(function() {
				doUpdate(value);
			});
		}

		function getData(value) {
			if (!value || isBinary) {
				return value;
			}
			return {
				id: value.id
			};
		}

		scope.$render_editable = function() {
			image.get(0).src = scope.getLink(model.$viewValue);
		};

		scope.$watch("record.id", function(id, old) {
			if (!scope.isReadonly()) {
				scope.$render_editable();
			}
		});
	},
	template_editable:
	'
' +
		'<input type="file" accept="image/*">' +
		'' +
		'
' +
			'<button ng-click="doSelect()" class="btn" type="button"></button>' +
			'<button ng-click="doRemove()" class="btn" type="button"></button>' +
		'
' +
	'
'
});

ui.formInput('Binary', {

	css: 'file-item',
	cellCss: 'form-item file-item',

	link: function(scope, element, attrs, model) {

		var field = scope.field;
		var input = element.children('input:first').hide();

		scope.doSelect = function() {
			input.click();
		};

		scope.doSave = function() {
			var record = scope.record;
			var model = scope._model;
			var url = makeURL(model, field.name, record);
			ui.download(url, record.fileName || field.name);
		};

		scope.doRemove = function() {
			var record = scope.record;
			input.val(null);
			model.$setViewValue(null);
			record.$upload = null;
			if(scope._model === META_FILE) {
				record.fileName = null;
				record.fileType = null;
			}
			record.fileSize = null;
		};

		scope.canDownload = function() {
			var record = scope.record || {};
			if (!record.id) return false;
			if (scope._model === META_FILE) {
				return !!record.fileName;
			}
			return true;
		};

		input.change(function(e) {
			var file = input.get(0).files[0];
			var record = scope.record;

			// reset file selection
			input.get(0).value = null;

			if (file) {
				record.$upload = {
					field: field.name,
					file: file
				};
				if(scope._model === META_FILE) {
					record.fileName = file.name;
				}
				record.fileType = file.type;
				record.fileSize = file.size;
				scope.applyLater(function() {
					model.$setViewValue(0); // mark form for save
				});
			}
		});
	},
	template_readonly: null,
	template_editable: null,
	template:
	'
' +
		'<input type="file">' +
		'
' +
			'<button ng-click="doSelect()" ng-show="!isReadonly()" class="btn" type="button"></button>' +
			'<button ng-click="doSave()" ng-show="canDownload()" class="btn" type="button"></button>' +
			'<button ng-click="doRemove()" ng-show="!isReadonly()" class="btn" type="button"></button>' +
		'
' +
	'
'
});

ui.formInput('BinaryLink', {

	css: 'file-item',
	cellCss: 'form-item file-item',

	link: function(scope, element, attrs, model) {

		var field = scope.field;
		var input = element.children('input:first').hide();

		if (field.target !== META_FILE) {
			throw new Error("BinaryLink widget can be used with MetaFile field only.");
		}

		scope.doSelect = function() {
			input.click();
		};

		scope.doRemove = function() {
			input.val(null);
			scope.setValue(null, true);
		};

		scope.canDownload = function() {
			var value = model.$viewValue;
			return value && value.id > 0;
		};

		scope.format = function (value) {
			if (value) {
				return value.fileName;
			}
			return value;
		};

		scope.doSave = function() {
			var value = model.$viewValue;
			var url = makeURL(META_FILE, "content", value);
			ui.download(url, scope.text);
		};

		input.change(function(e) {
			var file = input.get(0).files[0];

			// reset file selection
			input.get(0).value = null;

			if (!file) {
				return;
			}

			var ds = scope._dataSource._new(META_FILE);
			var value = scope.getValue() || {};
			var record = _.extend({
				fileName: file.name,
				fileType: file.type,
				fileSize: file.size
			}, {
				id: value.id,
				version: value.version || value.$version
			});

			record.$upload = {
				file: file
			};

			ds.save(record).success(function (rec) {
				scope.setValue(rec, true);
			});
		});
	},
	template_readonly: null,
	template_editable: null,
	template:
	'
' +
		'<input type="file">' +
		'
' +
			'<button ng-click="doSelect()" ng-show="!isReadonly()" class="btn" type="button"></button>' +
			'<button ng-click="doRemove()" ng-show="canDownload() && !isReadonly()" class="btn" type="button"></button>' +
		'
 ' +
		'{{text}}' +
	'
'
});

})();
<commit_msg>Fix regression<commit_after>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2015 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function() {

"use strict";

var ui = angular.module('axelor.ui');

var BLANK = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
var META_FILE = "com.axelor.meta.db.MetaFile";

function makeURL(model, field, recordOrId) {
	var value = recordOrId;
	if (!value) return null;
	var id = value.id ? value.id : value;
	var version = value.version || value.$version || (new Date()).getTime();
	if (!id || id <= 0) return null;
	return "ws/rest/" + model + "/" + id + "/" + field + "/download?v=" + version;
}

ui.makeImageURL = makeURL;

ui.formInput('ImageLink', {
	css: 'image-item',
	cssClass: 'from-item image-item',

	controller: ['$scope', '$element', '$interpolate', function($scope, $element, $interpolate) {

		$scope.parseText = function(text) {
			if (!text) return BLANK;
			if (!text.match(/{{.*?}}/)) {
				return text;
			}
			return $interpolate(text)($scope.record);
		};
	}],

	init: function(scope) {
		var field = scope.field;

		var width = field.width || 140;
		var height = field.height || '100%';

		scope.styles = [{
			'width': width,
			'max-width': '100%',
			'max-height': '100%'
		}, {
			'width': width,
			'height': height,
			'max-width': '100%',
			'max-height': '100%'
		}];

		if (field.noframe) {
			_.extend(scope.styles[1], {
				border: 0,
				padding: 0,
				background: 'none',
				boxShadow: 'none'
			});
		}
	},

	link_readonly: function(scope, element, attrs, model) {

		var image = element.children('img:first');

		scope.$render_readonly = function() {
			image.get(0).src = scope.parseText(model.$viewValue) || BLANK;
		};

		scope.$watch("record.id", function(id, old) {
			if (scope.isReadonly()) {
				scope.$render_readonly();
			}
		});
	},
	template_editable: '<input type="text">',
	template_readonly:
		'
'+
			''+
		'
'
});

ui.formInput('Image', 'ImageLink', {

	init: function(scope) {
		this._super.apply(this, arguments);

		var field = scope.field;
		var isBinary = field.serverType === 'binary';

		if (!isBinary && field.target !== META_FILE) {
			throw new Error("Invalid field type for Image widget.");
		}

		scope.parseText = function (value) {
			return scope.getLink(value);
		};

		scope.getLink = function (value) {
			var record = scope.record || {};
			var model = scope._model;
			if (!record.id || value === null) return value || BLANK;
			if (isBinary) {
				if (value) return value;
				return makeURL(model, field.name, record) + "&image=true";
			}
			return makeURL(META_FILE, "content", (value.id || value));
		};
	},

	link_editable: function(scope, element, attrs, model) {

		var field = scope.field;
		var input = element.children('input:first');
		var image = element.children('img:first');
		var buttons = element.children('.btn-group');

		var isBinary = field.serverType === 'binary';
		var timer = null;

		input.add(buttons).hide();
		element.on('mouseenter', function (e) {
			if (timer) clearTimeout(timer);
			timer = setTimeout(function () {
				buttons.slideDown();
			}, 500);
		});
		element.on('mouseleave', function (e) {
			if (timer) {
				clearTimeout(timer);
				timer = null;
			}
			buttons.slideUp();
		});

		scope.doSelect = function() {
			input.click();
		};

		scope.doSave = function() {
			var content = image.get(0).src;
			if (content) {
				window.open(content);
			}
		};

		scope.doRemove = function() {
			image.get(0).src = "";
			input.val(null);
			update(null);
		};

		input.change(function(e, ui) {
			var file = input.get(0).files[0];
			var uploadSize = axelor.config["file.upload.size"];

			// reset file selection
			input.get(0).value = null;

			if (!file) {
				return;
			}

			if(file.size > 1048576 * parseInt(uploadSize)) {
				return axelor.dialogs.say(_t("You are not allow to upload a file bigger than") + ' ' + uploadSize + 'MB');
			}

			if (!isBinary) {
				return doUpload(file);
			}

			var reader = new FileReader();
			reader.onload = function(e) {
				update(e.target.result, file.name);
			};

			reader.readAsDataURL(file);
		});

		function doUpload(file) {
			var ds = scope._dataSource._new(META_FILE);
			var value = field.target === META_FILE ? (scope.getValue()||{}) : {};
			var record = {
				fileName: file.name,
				fileType: file.type,
				fileSize: file.size,
				id: value.id,
				version: value.version || value.$version
		    };

			record.$upload = {
			    file: file
		    };

			ds.save(record).success(function (saved) {
				update(saved);
			});
		}

		function doUpdate(value) {
			image.get(0).src = scope.getLink(value);
			model.$setViewValue(getData(value));
		}

		function update(value) {
			scope.applyLater(function() {
				doUpdate(value);
			});
		}

		function getData(value) {
			if (!value || isBinary) {
				return value;
			}
			return {
				id: value.id
			};
		}

		scope.$render_editable = function() {
			image.get(0).src = scope.getLink(model.$viewValue);
		};

		scope.$watch("record.id", function(id, old) {
			if (!scope.isReadonly()) {
				scope.$render_editable();
			}
		});
	},
	template_editable:
	'
' +
		'<input type="file" accept="image/*">' +
		'' +
		'
' +
			'<button ng-click="doSelect()" class="btn" type="button"></button>' +
			'<button ng-click="doRemove()" class="btn" type="button"></button>' +
		'
' +
	'
'
});

ui.formInput('Binary', {

	css: 'file-item',
	cellCss: 'form-item file-item',

	link: function(scope, element, attrs, model) {

		var field = scope.field;
		var input = element.children('input:first').hide();

		scope.doSelect = function() {
			input.click();
		};

		scope.doSave = function() {
			var record = scope.record;
			var model = scope._model;
			var url = makeURL(model, field.name, record);
			ui.download(url, record.fileName || field.name);
		};

		scope.doRemove = function() {
			var record = scope.record;
			input.val(null);
			model.$setViewValue(null);
			record.$upload = null;
			if(scope._model === META_FILE) {
				record.fileName = null;
				record.fileType = null;
			}
			record.fileSize = null;
		};

		scope.canDownload = function() {
			var record = scope.record || {};
			if (!record.id) return false;
			if (scope._model === META_FILE) {
				return !!record.fileName;
			}
			return true;
		};

		input.change(function(e) {
			var file = input.get(0).files[0];
			var record = scope.record;

			// reset file selection
			input.get(0).value = null;

			if (file) {
				record.$upload = {
					field: field.name,
					file: file
				};
				if(scope._model === META_FILE) {
					record.fileName = file.name;
				}
				record.fileType = file.type;
				record.fileSize = file.size;
				scope.applyLater(function() {
					model.$setViewValue(0); // mark form for save
				});
			}
		});
	},
	template_readonly: null,
	template_editable: null,
	template:
	'
' +
		'<input type="file">' +
		'
' +
			'<button ng-click="doSelect()" ng-show="!isReadonly()" class="btn" type="button"></button>' +
			'<button ng-click="doSave()" ng-show="canDownload()" class="btn" type="button"></button>' +
			'<button ng-click="doRemove()" ng-show="!isReadonly()" class="btn" type="button"></button>' +
		'
' +
	'
'
});

ui.formInput('BinaryLink', {

	css: 'file-item',
	cellCss: 'form-item file-item',

	link: function(scope, element, attrs, model) {

		var field = scope.field;
		var input = element.children('input:first').hide();

		if (field.target !== META_FILE) {
			throw new Error("BinaryLink widget can be used with MetaFile field only.");
		}

		scope.doSelect = function() {
			input.click();
		};

		scope.doRemove = function() {
			input.val(null);
			scope.setValue(null, true);
		};

		scope.canDownload = function() {
			var value = model.$viewValue;
			return value && value.id > 0;
		};

		scope.format = function (value) {
			if (value) {
				return value.fileName;
			}
			return value;
		};

		scope.doSave = function() {
			var value = model.$viewValue;
			var url = makeURL(META_FILE, "content", value);
			ui.download(url, scope.text);
		};

		input.change(function(e) {
			var file = input.get(0).files[0];

			// reset file selection
			input.get(0).value = null;

			if (!file) {
				return;
			}

			var ds = scope._dataSource._new(META_FILE);
			var value = scope.getValue() || {};
			var record = _.extend({
				fileName: file.name,
				fileType: file.type,
				fileSize: file.size
			}, {
				id: value.id,
				version: value.version || value.$version
			});

			record.$upload = {
				file: file
			};

			ds.save(record).success(function (rec) {
				scope.setValue(rec, true);
			});
		});
	},
	template_readonly: null,
	template_editable: null,
	template:
	'
' +
		'<input type="file">' +
		'
' +
			'<button ng-click="doSelect()" ng-show="!isReadonly()" class="btn" type="button"></button>' +
			'<button ng-click="doRemove()" ng-show="canDownload() && !isReadonly()" class="btn" type="button"></button>' +
		'
 ' +
		'{{text}}' +
	'
'
});

})();
<|endoftext|>


<commit_before>Spree.ready(function() {
  var $gateway_type = $('select.js-gateway-type');
  var $preference_source = $('select.js-preference-source');
  var original_gtwy_type = $gateway_type.val();
  var original_preference_source = $preference_source.val();

  var render = function() {
    var gateway_type = $gateway_type.val();
    var preference_source = $preference_source.val();
    $('.js-preference-source-wrapper').toggle(gateway_type === original_gtwy_type);
    if (gateway_type === original_gtwy_type && preference_source === original_preference_source) {
      $('.js-gateway-settings').show();
      $('.js-gateway-settings-warning').hide();
    } else {
      $('.js-gateway-settings').hide();
      $('.js-gateway-settings-warning').show();
    }
  };
  $gateway_type.change(render);
  $preference_source.change(render);
  render();
});
<commit_msg>s/original_gtwy_type/original_gateway_type/g<commit_after>Spree.ready(function() {
  var $gateway_type = $('select.js-gateway-type');
  var $preference_source = $('select.js-preference-source');
  var original_gateway_type = $gateway_type.val();
  var original_preference_source = $preference_source.val();

  var render = function() {
    var gateway_type = $gateway_type.val();
    var preference_source = $preference_source.val();
    $('.js-preference-source-wrapper').toggle(gateway_type === original_gateway_type);
    if (gateway_type === original_gateway_type && preference_source === original_preference_source) {
      $('.js-gateway-settings').show();
      $('.js-gateway-settings-warning').hide();
    } else {
      $('.js-gateway-settings').hide();
      $('.js-gateway-settings-warning').show();
    }
  };
  $gateway_type.change(render);
  $preference_source.change(render);
  render();
});
<|endoftext|>


<commit_before>
Array.prototype.__in_groups_of = function(n) {
  var length = this.length,
      group_size = Math.ceil(length / n),
      groups = [];
  for(var i=0; i<n; i++) {
    groups.push(this.slice((i*group_size), ((i+1)*group_size)) || []);
  }
  return groups;
}
if(!Array.prototype.in_groups_of) Array.prototype.in_groups_of = Array.prototype.__in_groups_of;

Array.prototype.__group_by = function(fn) {
  var hash = {}, key, array;
  for(var i=0, ii=this.length; i<ii; i++) {
    key = fn(this[i]);
    array = hash[key] || [];
    array.push(this[i]);
    hash[key] = array;
  }
  return hash;
}
if(!Array.prototype.groupBy) Array.prototype.groupBy = Array.prototype.__group_by;

Array.prototype.__includes = function(item) {
  for(var i=0, ii=this.length; i<ii; i++) {
    if(this[i] == item) {
      return true;
    }
  }
  return false;
}
if(!Array.prototype.includes) Array.prototype.includes = Array.prototype.__includes;
if(!Array.prototype.include) Array.prototype.include = Array.prototype.__includes;
if(!Array.prototype.contains) Array.prototype.contains = Array.prototype.__includes;
if(!Array.prototype.contain) Array.prototype.contain = Array.prototype.__includes;

Array.prototype.__each = function(fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    fn(this[i]);
  }
}
if(!Array.prototype.each) Array.prototype.each = Array.prototype.__each;

Array.prototype.__collect = function(fn) {
  var array = [];
  for(var i=0, ii=this.length; i<ii; i++) {
    array.push(fn(this[i]));
  }
  return array;
}
if(!Array.prototype.collect) Array.prototype.collect = Array.prototype.__collect;
if(!Array.prototype.map) Array.prototype.map = Array.prototype.__collect;

Array.__each = function(array, fn) {
  for(var i=0, ii=array.length; i<ii; i++) {
    fn(array[i]);
  }
}
if(!Array.each) Array.each = Array.__each;

Array.prototype.__find = function(fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    var e = this[i];
    if(fn(e)) {
      return e;
    }
  }
  return null;
}
if(!Array.prototype.find) Array.prototype.find = Array.prototype.__find;
if(!Array.prototype.detect) Array.prototype.detect = Array.prototype.__find;

Array.prototype.__inject = function(memo, fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    memo = fn(memo, this[i]);
  }
  return memo;
}
if(!Array.prototype.inject) Array.prototype.inject = Array.prototype.__inject;
if(!Array.prototype.reduce) Array.prototype.reduce = Array.prototype.__inject;

Array.prototype.__eachWithObject = function(memo, fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    fn(memo, this[i]);
  }
  return memo;
}
if(!Array.prototype.eachWithObject) Array.prototype.eachWithObject = Array.prototype.__eachWithObject;

Array.prototype.__grep = function(regex) {
  return this.__select(function(e) {
    return e.toString().match(regex);
  });
}
if(!Array.prototype.grep) Array.prototype.grep = Array.prototype.__grep;

Array.prototype.__remove = function(removeMe) {
  for(var i=0, ii=this.length; i<ii; i++) {
    if(this[i]==removeMe) {
      this.splice(i, 1);
      ii--;
      i--;
    }
  }
}
if(!Array.prototype.remove) Array.prototype.remove = Array.prototype.__remove;

Array.prototype.__removeWith = function(fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    if(fn(this[i])) {
      this.splice(i, 1);
      ii--;
      i--;
    }
  }
}
if(!Array.prototype.removeWith) Array.prototype.removeWith = Array.prototype.__removeWith;
if(!Array.prototype.removeIf) Array.prototype.removeIf = Array.prototype.__removeWith;

Array.prototype.__select = function(fn) {
  var selected = [];
  for(var i=0, ii=this.length; i<ii; i++) {
    if(fn(this[i])) {
      selected.push(this[i]);
    }
  }
  return selected;
}
if(!Array.prototype.select) Array.prototype.select = Array.prototype.__select;
if(!Array.prototype.findAll) Array.prototype.findAll = Array.prototype.__select;

Array.prototype.__count_of = function(fn) {
  var count = 0;
  for(var i=0, ii=this.length; i<ii; i++) {
    if(fn(this[i])) {
      count += 1;
    }
  }
  return count;
}
if(!Array.prototype.countOf) Array.prototype.countOf = Array.prototype.__count_of;

Array.prototype.__dup = function() {
  return this.slice(0);
}
if(!Array.prototype.dup) Array.prototype.dup = Array.prototype.__dup;

Array.prototype.__first = function() {
  return this[0];
}
if(!Array.prototype.first) Array.prototype.first = Array.prototype.__first;

Array.prototype.__last = function() {
  return this[this.length - 1];
}
if(!Array.prototype.last) Array.prototype.last = Array.prototype.__last;
<commit_msg>added indexOf to Array for backwards-compatibility from Javascript 1.6<commit_after>
Array.prototype.__in_groups_of = function(n) {
  var length = this.length,
      group_size = Math.ceil(length / n),
      groups = [];
  for(var i=0; i<n; i++) {
    groups.push(this.slice((i*group_size), ((i+1)*group_size)) || []);
  }
  return groups;
}
if(!Array.prototype.in_groups_of) Array.prototype.in_groups_of = Array.prototype.__in_groups_of;

Array.prototype.__index_of = function(n) {
  for(var i=0, ii=this.length; i<ii; i++) {
    var e = this[i];
    if(e == n) {
      return i;
    }
  }
  return -1;
}
if(!Array.prototype.indexOf) Array.prototype.indexOf = Array.prototype.__index_of;

Array.prototype.__group_by = function(fn) {
  var hash = {}, key, array;
  for(var i=0, ii=this.length; i<ii; i++) {
    key = fn(this[i]);
    array = hash[key] || [];
    array.push(this[i]);
    hash[key] = array;
  }
  return hash;
}
if(!Array.prototype.groupBy) Array.prototype.groupBy = Array.prototype.__group_by;

Array.prototype.__includes = function(item) {
  for(var i=0, ii=this.length; i<ii; i++) {
    if(this[i] == item) {
      return true;
    }
  }
  return false;
}
if(!Array.prototype.includes) Array.prototype.includes = Array.prototype.__includes;
if(!Array.prototype.include) Array.prototype.include = Array.prototype.__includes;
if(!Array.prototype.contains) Array.prototype.contains = Array.prototype.__includes;
if(!Array.prototype.contain) Array.prototype.contain = Array.prototype.__includes;

Array.prototype.__each = function(fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    fn(this[i]);
  }
}
if(!Array.prototype.each) Array.prototype.each = Array.prototype.__each;

Array.prototype.__collect = function(fn) {
  var array = [];
  for(var i=0, ii=this.length; i<ii; i++) {
    array.push(fn(this[i]));
  }
  return array;
}
if(!Array.prototype.collect) Array.prototype.collect = Array.prototype.__collect;
if(!Array.prototype.map) Array.prototype.map = Array.prototype.__collect;

Array.__each = function(array, fn) {
  for(var i=0, ii=array.length; i<ii; i++) {
    fn(array[i]);
  }
}
if(!Array.each) Array.each = Array.__each;

Array.prototype.__find = function(fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    var e = this[i];
    if(fn(e)) {
      return e;
    }
  }
  return null;
}
if(!Array.prototype.find) Array.prototype.find = Array.prototype.__find;
if(!Array.prototype.detect) Array.prototype.detect = Array.prototype.__find;

Array.prototype.__inject = function(memo, fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    memo = fn(memo, this[i]);
  }
  return memo;
}
if(!Array.prototype.inject) Array.prototype.inject = Array.prototype.__inject;
if(!Array.prototype.reduce) Array.prototype.reduce = Array.prototype.__inject;

Array.prototype.__eachWithObject = function(memo, fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    fn(memo, this[i]);
  }
  return memo;
}
if(!Array.prototype.eachWithObject) Array.prototype.eachWithObject = Array.prototype.__eachWithObject;

Array.prototype.__grep = function(regex) {
  return this.__select(function(e) {
    return e.toString().match(regex);
  });
}
if(!Array.prototype.grep) Array.prototype.grep = Array.prototype.__grep;

Array.prototype.__remove = function(removeMe) {
  for(var i=0, ii=this.length; i<ii; i++) {
    if(this[i]==removeMe) {
      this.splice(i, 1);
      ii--;
      i--;
    }
  }
}
if(!Array.prototype.remove) Array.prototype.remove = Array.prototype.__remove;

Array.prototype.__removeWith = function(fn) {
  for(var i=0, ii=this.length; i<ii; i++) {
    if(fn(this[i])) {
      this.splice(i, 1);
      ii--;
      i--;
    }
  }
}
if(!Array.prototype.removeWith) Array.prototype.removeWith = Array.prototype.__removeWith;
if(!Array.prototype.removeIf) Array.prototype.removeIf = Array.prototype.__removeWith;

Array.prototype.__select = function(fn) {
  var selected = [];
  for(var i=0, ii=this.length; i<ii; i++) {
    if(fn(this[i])) {
      selected.push(this[i]);
    }
  }
  return selected;
}
if(!Array.prototype.select) Array.prototype.select = Array.prototype.__select;
if(!Array.prototype.findAll) Array.prototype.findAll = Array.prototype.__select;

Array.prototype.__count_of = function(fn) {
  var count = 0;
  for(var i=0, ii=this.length; i<ii; i++) {
    if(fn(this[i])) {
      count += 1;
    }
  }
  return count;
}
if(!Array.prototype.countOf) Array.prototype.countOf = Array.prototype.__count_of;

Array.prototype.__dup = function() {
  return this.slice(0);
}
if(!Array.prototype.dup) Array.prototype.dup = Array.prototype.__dup;

Array.prototype.__first = function() {
  return this[0];
}
if(!Array.prototype.first) Array.prototype.first = Array.prototype.__first;

Array.prototype.__last = function() {
  return this[this.length - 1];
}
if(!Array.prototype.last) Array.prototype.last = Array.prototype.__last;
<|endoftext|>


<commit_before>/**
 * @copyright Copyright (c) 2014 2amigOS! Consulting Group LLC
 * @link http://2amigos.us
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */
if (typeof dosamigos == "undefined" || !dosamigos) {
    var dosamigos = {};
}

dosamigos.ckEditorWidget = (function ($) {

    var pub = {
        registerOnChangeHandler: function (id) {
            CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () {
                CKEDITOR.instances[id].updateElement();
                $('#' + id).trigger('change');
                return false;
            });
        },
        registerCsrfImageUploadHandler: function () {
            yii & $(document).off('click', '.cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(2)', function () {
                var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form');
                if (!$form.find('input[name=_csrf]').length) {
                    var csrfTokenInput = $('<input/>').attr({'type': 'hidden', 'name': yii.getCsrfParam()}).val(yii.getCsrfToken());
                    $form.append(csrfTokenInput);
                }
            });
        }
    };
    return pub;
})(jQuery);
<commit_msg>Update dosamigos-ckeditor.widget.js<commit_after>/**
 * @copyright Copyright (c) 2014 2amigOS! Consulting Group LLC
 * @link http://2amigos.us
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */
if (typeof dosamigos == "undefined" || !dosamigos) {
    var dosamigos = {};
}

dosamigos.ckEditorWidget = (function ($) {

    var pub = {
        registerOnChangeHandler: function (id) {
            CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () {
                CKEDITOR.instances[id].updateElement();
                $('#' + id).trigger('change');
                return false;
            });
        },
        registerCsrfImageUploadHandler: function () {
            yii & $(document).off('click', '.cke_dialog_tabs a:eq(2)').on('click', '.cke_dialog_tabs a:eq(2)', function () {
                var $form = $('.cke_dialog_ui_input_file iframe').contents().find('form');
                var csrfName = yii.getCsrfParam();
                if (!$form.find('input[name=' + csrfName + ']').length) {
                    var csrfTokenInput = $('<input/>').attr({'type': 'hidden', 'name': csrfName}).val(yii.getCsrfToken());
                    $form.append(csrfTokenInput);
                }
            });
        }
    };
    return pub;
})(jQuery);
<|endoftext|>


<commit_before>(function() {
    klp.init = function() {
        $('#organization').val(ORGANIZATION_ID);
        var formID = 'activityForm';
        var $school = $('#school');
        klp.utils.schoolSelect2($school);
        $('#' + formID).submit(function(e) {
            if (e) {
                e.preventDefault();
            }
            var fields = {
                'type': $('#activityType'),
                'organization': $('#organization'),
                'school': $('#school'),
                'date': $('#date'),
                'text': $('#text')
            };

            var data = klp.utils.getFormData(fields);
            //console.log("data", data);
            var url = "volunteer_activities";

            var $xhr = klp.api.authDo(url, data, 'POST');

            $xhr.done(function(response) {
                console.log("saved", response);
                alert("saved");
                location.href = "/organisation/" + ORGANIZATION_ID;
            });

            $xhr.fail(function(err) {
                var errors = JSON.parse(err.responseText);
                klp.utils.invalidateErrors(errors);
                console.log("error", err);
            });

        });

    };

})();<commit_msg>after adding volunteer opportunity, reload page to add another, refs #231<commit_after>(function() {
    klp.init = function() {
        $('#organization').val(ORGANIZATION_ID);
        var formID = 'activityForm';
        var $school = $('#school');
        klp.utils.schoolSelect2($school);
        $('#' + formID).submit(function(e) {
            if (e) {
                e.preventDefault();
            }
            var fields = {
                'type': $('#activityType'),
                'organization': $('#organization'),
                'school': $('#school'),
                'date': $('#date'),
                'text': $('#text')
            };

            var data = klp.utils.getFormData(fields);
            //console.log("data", data);
            var url = "volunteer_activities";

            var $xhr = klp.api.authDo(url, data, 'POST');

            $xhr.done(function(response) {
                console.log("saved", response);
                alert("saved");
                location.reload();
                //location.href = "/organisation/" + ORGANIZATION_ID;
            });

            $xhr.fail(function(err) {
                var errors = JSON.parse(err.responseText);
                klp.utils.invalidateErrors(errors);
                console.log("error", err);
            });

        });

    };

})();<|endoftext|>


<commit_before>"use strict"
const pry = require('pryjs');

const request = require('koa-request');
const qs = require('qs');
const _ = require('lodash');
const log = require('log-colors');

const DATA_HOST = "https://storage.scrapinghub.com";
const PROJECT_ID = process.env['PROJECT_ID'];
const API_KEY = process.env['STORAGE_KEY'];

const CONNECT_TIMEOUT = 200;
const REQUEST_TIMEOUT = 200;

class Store {
  constructor(){
    this.collection = [];
    this.tags = [];
  }

  update(){
    log.info('updating statistics');
    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "json",
      "meta": ["_key"],
      "nodata": "1"
    }, { arrayFormat: 'repeat' });
    var filter_param = '%5B%22content%22%2C%22matches%22%2C%5B%22(zippyshare|mediafire|mega\.nz)%22%5D%5D';
    var url = `${DATA_HOST}/items/${PROJECT_ID}?${query_string}&filterany=${filter_param}`;

    return new Promise((resolve) => {
      request(url)((error, response) => resolve(response, error));
    }).then((response, error) => {
      this.collection = _.map(JSON.parse(response.body), item => item._key);
      log.info('statistics updated');
    });
  }

  update_tags(){
    log.info('updating tags');
    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "csv",
      "fields": "tags",
      "include_headers": "0",
      "escape": " ",
      "quote": " "
    }, { arrayFormat: 'repeat' });
    var filter_param = '%5B%22content%22%2C%22matches%22%2C%5B%22(zippyshare|mediafire|mega\.nz)%22%5D%5D';
    var url = `${DATA_HOST}/items/${PROJECT_ID}?${query_string}&filterany=${filter_param}`

    return new Promise((resolve) => {
      request(url)((error, response) => resolve(response, error));
    }).then((response, error) => {
      this.tags = _.reduce(response.body.split('\n'), (result, value, key) => {
        if(value === ''){ return result; }
        try {
          var tags = JSON.parse(value);
        } catch(e) {
          log.error('error parsing line: ' + value);
        }
        _.each(tags, (value, key) => {
          var _key = key
                     //.toLowerCase()
                     .replace(/^\*+/, '').replace(/\*+$/, '')
                     .replace(/genre: /i, '')
                     .replace(/label: /i, '')
                     .replace(/country: /i, '')
                     //.replace('and', '&')
                     .replace(/^-/, '')
                     .replace(/^#/, '')
                     .replace(/^¬/, '')
                     .replace(/^=/, '')
                     .replace(/^\./, '')
                     .replace(/^\+/, '')
                     .replace(/^\[/, '').replace(/\]$/, '')
                     .replace(/^\s+/, '')
                     .replace(/\s{2,}/g, ' ')
          result[_key] = result[_key] || 0;
          result[_key]++;
        });
        return result;
      }, {});
      log.info('tags updated');
    });
  }

  get_random(){
    var random_post_key = _.sample(this.collection);

    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "json",
      "meta": ["_key"]
    }, { arrayFormat: 'repeat' });

    var url = `${DATA_HOST}/items/${random_post_key}?${query_string}`;

    return request(url);
  }

  get_by_tags(tags){
    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "json",
      "count": 100,
      "meta": ["_key"]
    }, { arrayFormat: 'repeat' });
    var filter_param = encodeURIComponent('["tags","matches",["' + _.map(tags, tag => {
      return tag
             .replace('*', '\\\\*')
             .replace("[", "\\\\[")
             .replace("]", "\\\\]")
             .replace("(", "\\\\(")
             .replace(")", "\\\\)")
             .replace(/\s{2,}/g, ' ')
    }).join('|') + '"]]');
    var file_hostings_param = '%5B%22content%22%2C%22matches%22%2C%5B%22(zippyshare|mediafire|mega\.nz)%22%5D%5D';
    var url = `${DATA_HOST}/items/${PROJECT_ID}?${query_string}&filterany=${filter_param}&filterany=${file_hostings_param}`;

    return request(url);
  }
}

module.exports = Store;
<commit_msg>add more hostings<commit_after>"use strict"
const pry = require('pryjs');

const request = require('koa-request');
const qs = require('qs');
const _ = require('lodash');
const log = require('log-colors');

const DATA_HOST = "https://storage.scrapinghub.com";
const PROJECT_ID = process.env['PROJECT_ID'];
const API_KEY = process.env['STORAGE_KEY'];

const CONNECT_TIMEOUT = 200;
const REQUEST_TIMEOUT = 200;

/*
rusfolder.com
myupload.dk
uloz.to
uploaded.net
yadi.sk
copy.com

vk.com
soundcloud.com
youtube.com

nitroflare.com - complicated
gigasize.com - waiting
filefactory.com - waiting
turbobit.net - captcha + ip block

*/
const hostings = "zippyshare|mediafire|mega\.nz|rusfolder\.com|myupload\.dk|uloz\.to|uploaded\.net|yadi\.sk|copy\.com|nitroflare\.com|gigasize\.com|filefactory\.com|turbobit\.net|soundcloud\.com";

class Store {
  constructor(){
    this.collection = [];
    this.tags = [];
  }

  update(){
    log.info('updating statistics');
    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "json",
      "meta": ["_key"],
      "nodata": "1"
    }, { arrayFormat: 'repeat' });
    var filter_param = '%5B%22content%22%2C%22matches%22%2C%5B%22(' + hostings + ')%22%5D%5D';
    var url = `${DATA_HOST}/items/${PROJECT_ID}?${query_string}&filterany=${filter_param}`;

    return new Promise((resolve) => {
      request(url)((error, response) => resolve(response, error));
    }).then((response, error) => {
      this.collection = _.map(JSON.parse(response.body), item => item._key);
      log.info('statistics updated');
    });
  }

  update_tags(){
    log.info('updating tags');
    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "csv",
      "fields": "tags",
      "include_headers": "0",
      "escape": " ",
      "quote": " "
    }, { arrayFormat: 'repeat' });
    var filter_param = '%5B%22content%22%2C%22matches%22%2C%5B%22(' + hostings + ')%22%5D%5D';
    var url = `${DATA_HOST}/items/${PROJECT_ID}?${query_string}&filterany=${filter_param}`

    return new Promise((resolve) => {
      request(url)((error, response) => resolve(response, error));
    }).then((response, error) => {
      this.tags = _.reduce(response.body.split('\n'), (result, value, key) => {
        if(value === ''){ return result; }
        try {
          var tags = JSON.parse(value);
        } catch(e) {
          log.error('error parsing line: ' + value);
        }
        _.each(tags, (value, key) => {
          var _key = key
                     //.toLowerCase()
                     .replace(/^\*+/, '').replace(/\*+$/, '')
                     .replace(/genre: /i, '')
                     .replace(/label: /i, '')
                     .replace(/country: /i, '')
                     //.replace('and', '&')
                     .replace(/^-/, '')
                     .replace(/^#/, '')
                     .replace(/^¬/, '')
                     .replace(/^=/, '')
                     .replace(/^\./, '')
                     .replace(/^\+/, '')
                     .replace(/^\[/, '').replace(/\]$/, '')
                     .replace(/^\s+/, '')
                     .replace(/\s{2,}/g, ' ')
          result[_key] = result[_key] || 0;
          result[_key]++;
        });
        return result;
      }, {});
      log.info('tags updated');
    });
  }

  get_random(){
    var random_post_key = _.sample(this.collection);

    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "json",
      "meta": ["_key"]
    }, { arrayFormat: 'repeat' });

    var url = `${DATA_HOST}/items/${random_post_key}?${query_string}`;

    return request(url);
  }

  get_by_tags(tags){
    var query_string = qs.stringify({
      "apikey": API_KEY,
      "format": "json",
      "count": 100,
      "meta": ["_key"]
    }, { arrayFormat: 'repeat' });
    var filter_param = encodeURIComponent('["tags","matches",["' + _.map(tags, tag => {
      return tag
             .replace('*', '\\\\*')
             .replace("[", "\\\\[")
             .replace("]", "\\\\]")
             .replace("(", "\\\\(")
             .replace(")", "\\\\)")
             .replace(/\s{2,}/g, ' ')
    }).join('|') + '"]]');
    var file_hostings_param = '%5B%22content%22%2C%22matches%22%2C%5B%22(' + hostings + ')%22%5D%5D';
    var url = `${DATA_HOST}/items/${PROJECT_ID}?${query_string}&filterany=${filter_param}&filterany=${file_hostings_param}`;

    return request(url);
  }
}

module.exports = Store;
<|endoftext|>


<commit_before>(function(angular){
	"use strict";
        angular.module("mde.swipeToRefresh")
		.directive("mdeSwipeToRefresh", mdeSwipeToRefreshDirective);

	var State = {
		None: "None",
		Updating: "Updating",
		Pulling: "Pulling"
	};

	function mdeSwipeToRefreshDirective($q, $timeout, mdeSwipeToRefreshConfig){
		return{
			restrict: "A",
            require: "?^mdeSwipeToRefreshScrollHost",
			transclude: true,
			scope:{
                mdeOnRefresh: "&?",
                mdeOnCancel: "&?",
                mdeScrollHostSelector: "@?",
                mdeThreshold: "=?"
			},
			templateUrl: "swipe-to-refresh/swipe-to-refresh.html",
			link: linkFn
		};

		function linkFn(scope, elem, attrs, mdeSwipeToRefreshScrollHost){
			elem.bind("touchstart", touchStart);
			var scrollHost, startY;
			if(mdeSwipeToRefreshScrollHost){
                scrollHost = mdeSwipeToRefreshScrollHost.getElement();
            }
            else if(scope.mdeScrollHostSelector){
			    var el = elem.parent();
			    while( el[0] != document.body){
                    el = el.parent();
                    if(el[0].matches(scope.mdeScrollHostSelector)){
                        scrollHost = el;
                        break;
                    }
                }
                // if mdeScrollHostSelector doesn't matches anything, fallback to body
                scrollHost = scrollHost || el;
            }
            else{
                // default to body
                scrollHost = angular.element(document.body);
            }
            scope.mdeThreshold = scope.mdeThreshold || mdeSwipeToRefreshConfig.threshold;

            scope.State = State;
            scope.progress = 0;
            scope.state = State.None;

            function touchStart(event){
                if(scope.state != State.None){
                    return;
                }
                startY = event.touches[0].pageY;
                elem.one("touchend", touchEnd);
                elem.bind("touchmove", touchMove);

                if(scrollHost[0].scrollTop == 0){
                    scope.progress = 0;
                    scope.movement = 0;
                    scope.$digest();
                }
            }

            function touchMove(event) {
                if(scrollHost[0].scrollTop > 0){
                    return;
                }
                var movement = event.touches[0].pageY - startY;

                if(movement > 0 && scope.state != State.Pulling){
                    $timeout(function (){
                        scope.state = State.Pulling;
                    })
                }

                if(scope.state == State.Pulling){
                    event.preventDefault();
                }

                if(movement > 0){
                    scope.movement = Math.min(calculateMovement(movement, scope.mdeThreshold));
                    scope.progress = Math.min( scope.movement/scope.mdeThreshold, 1);
                    scope.$digest();
				}
				else if(scope.movement > 0){
                    scope.movement = 0;
                    scope.progress = 0;
                    scope.$digest();
                }

            }
            function touchEnd(event){
                elem.unbind("touchmove", touchMove);
                scope.$apply(function(){
                	if(scope.progress == 1){
                        scope.state = State.Updating;
                        scope.movement = scope.mdeThreshold;
                        $q.when((scope.mdeOnRefresh || angular.noop)()).finally(function(){
                            scope.state = State.None;
                        })
                    }
                    else{
                        if(scope.movement > 0){
                            (scope.mdeOnCancel || angular.noop)();
                            scope.movement = 0;
                        }
                        $timeout(function(){
                            scope.state = State.None;
                        },100);
					}
                });
            }
		}
	}
    function calculateMovement(movement, activationThreshold) {
        /*
         These are observations on Nexus 5 for how pulling is calculated based on touch movement.
         It seems there is kind of a logarithmic relation going on (as it also feels so).
         Note that Pixels need to be divided by 3 to become comparable to web (assuming proper viewport tag exists)

         touch movement(x)	=> 	pull (y)
         72, 40
         170, 100
         240, 143
         304, 180 => near threshold
         448, 250
         592, 310
         745, 360
         904, 395
         1254, 430
         * */
        return 2 * activationThreshold * log10((movement + activationThreshold) / activationThreshold);
    }
    function log10(x){
        return Math.log(x)/Math.LN10;
        // we don't use Math.log10 as it's only available in ES6
    }
})(angular);<commit_msg>fix: clear progress and movement after successful update<commit_after>(function(angular){
	"use strict";
        angular.module("mde.swipeToRefresh")
		.directive("mdeSwipeToRefresh", mdeSwipeToRefreshDirective);

	var State = {
		None: "None",
		Updating: "Updating",
		Pulling: "Pulling"
	};

	function mdeSwipeToRefreshDirective($q, $timeout, mdeSwipeToRefreshConfig){
		return{
			restrict: "A",
            require: "?^mdeSwipeToRefreshScrollHost",
			transclude: true,
			scope:{
                mdeOnRefresh: "&?",
                mdeOnCancel: "&?",
                mdeScrollHostSelector: "@?",
                mdeThreshold: "=?"
			},
			templateUrl: "swipe-to-refresh/swipe-to-refresh.html",
			link: linkFn
		};

		function linkFn(scope, elem, attrs, mdeSwipeToRefreshScrollHost){
			elem.bind("touchstart", touchStart);
			var scrollHost, startY;
			if(mdeSwipeToRefreshScrollHost){
                scrollHost = mdeSwipeToRefreshScrollHost.getElement();
            }
            else if(scope.mdeScrollHostSelector){
			    var el = elem.parent();
			    while( el[0] != document.body){
                    el = el.parent();
                    if(el[0].matches(scope.mdeScrollHostSelector)){
                        scrollHost = el;
                        break;
                    }
                }
                // if mdeScrollHostSelector doesn't matches anything, fallback to body
                scrollHost = scrollHost || el;
            }
            else{
                // default to body
                scrollHost = angular.element(document.body);
            }
            scope.mdeThreshold = scope.mdeThreshold || mdeSwipeToRefreshConfig.threshold;

            scope.State = State;
            scope.progress = 0;
            scope.state = State.None;

            function touchStart(event){
                if(scope.state != State.None){
                    return;
                }
                startY = event.touches[0].pageY;
                elem.one("touchend", touchEnd);
                elem.bind("touchmove", touchMove);

                if(scrollHost[0].scrollTop == 0){
                    scope.progress = 0;
                    scope.movement = 0;
                    scope.$digest();
                }
            }

            function touchMove(event) {
                if(scrollHost[0].scrollTop > 0){
                    return;
                }
                var movement = event.touches[0].pageY - startY;

                if(movement > 0 && scope.state != State.Pulling){
                    $timeout(function (){
                        scope.state = State.Pulling;
                    })
                }

                if(scope.state == State.Pulling){
                    event.preventDefault();
                }

                if(movement > 0){
                    scope.movement = Math.min(calculateMovement(movement, scope.mdeThreshold));
                    scope.progress = Math.min( scope.movement/scope.mdeThreshold, 1);
                    scope.$digest();
				}
				else if(scope.movement > 0){
                    scope.movement = 0;
                    scope.progress = 0;
                    scope.$digest();
                }

            }
            function touchEnd(event){
                elem.unbind("touchmove", touchMove);
                scope.$apply(function(){
                	if(scope.progress == 1){
                        scope.state = State.Updating;
                        scope.movement = scope.mdeThreshold;
                        $q.when((scope.mdeOnRefresh || angular.noop)()).finally(function(){
                            scope.state = State.None;
                            scope.movement = 0;
                            scope.progress = 0;
                        })
                    }
                    else{
                        if(scope.movement > 0){
                            (scope.mdeOnCancel || angular.noop)();
                            scope.movement = 0;
                            scope.progress = 0;
                        }
                        $timeout(function(){
                            scope.state = State.None;
                        },100);
					}
                });
            }
		}
	}
    function calculateMovement(movement, activationThreshold) {
        /*
         These are observations on Nexus 5 for how pulling is calculated based on touch movement.
         It seems there is kind of a logarithmic relation going on (as it also feels so).
         Note that Pixels need to be divided by 3 to become comparable to web (assuming proper viewport tag exists)

         touch movement(x)	=> 	pull (y)
         72, 40
         170, 100
         240, 143
         304, 180 => near threshold
         448, 250
         592, 310
         745, 360
         904, 395
         1254, 430
         * */
        return 2 * activationThreshold * log10((movement + activationThreshold) / activationThreshold);
    }
    function log10(x){
        return Math.log(x)/Math.LN10;
        // we don't use Math.log10 as it's only available in ES6
    }
})(angular);<|endoftext|>


<commit_before>/**
 * Create the store with asynchronously loaded reducers
 */

import { createStore, applyMiddleware, compose } from 'redux'
import { fromJS } from 'immutable'
import { routerMiddleware } from 'react-router-redux'
// import { persistStore, autoRehydrate } from 'redux-persist'
import { persistStore, autoRehydrate } from 'redux-persist-immutable'
// on sagas by hand, not automated:
// import { loadingBarMiddleware } from 'react-redux-loading-bar'
import createSagaMiddleware from 'redux-saga'
import appSaga from 'containers/App/sagas'
import createReducer from './reducers'

const sagaMiddleware = createSagaMiddleware()

export default function configureStore(initialState = {}, history) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history) /* ,
    loadingBarMiddleware({
      promiseTypeSuffixes: ['REQUEST', 'SUCCESS', 'FAILURE']
    }) */
  ]

  const enhancers = [
    applyMiddleware(...middlewares),
    autoRehydrate()
  ]

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
      window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  )

  // begin periodically persisting the store
  persistStore(store, { blacklist: 'route' })

  // Extensions

  // run saga from 'containers/App/sagas' here
  sagaMiddleware.run(appSaga)

  store.runSaga = sagaMiddleware.run
  store.asyncReducers = {} // Async reducer registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      System.import('./reducers').then((reducerModule) => {
        const createReducers = reducerModule.default
        const nextReducers = createReducers(store.asyncReducers)

        store.replaceReducer(nextReducers)
      })
    })
  }

  return store
}
<commit_msg>update blacklist persist storage<commit_after>/**
 * Create the store with asynchronously loaded reducers
 */

import { createStore, applyMiddleware, compose } from 'redux'
import { fromJS } from 'immutable'
import { routerMiddleware } from 'react-router-redux'
// import { persistStore, autoRehydrate } from 'redux-persist'
import { persistStore, autoRehydrate } from 'redux-persist-immutable'
// on sagas by hand, not automated:
// import { loadingBarMiddleware } from 'react-redux-loading-bar'
import createSagaMiddleware from 'redux-saga'
import appSaga from 'containers/App/sagas'
import createReducer from './reducers'

const sagaMiddleware = createSagaMiddleware()

export default function configureStore(initialState = {}, history) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history) /* ,
    loadingBarMiddleware({
      promiseTypeSuffixes: ['REQUEST', 'SUCCESS', 'FAILURE']
    }) */
  ]

  const enhancers = [
    applyMiddleware(...middlewares),
    autoRehydrate()
  ]

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
      window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  )

  // begin periodically persisting the store
  persistStore(store, { blacklist: ['route', 'loadingBar'] })

  // Extensions

  // run saga from 'containers/App/sagas' here
  sagaMiddleware.run(appSaga)

  store.runSaga = sagaMiddleware.run
  store.asyncReducers = {} // Async reducer registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      System.import('./reducers').then((reducerModule) => {
        const createReducers = reducerModule.default
        const nextReducers = createReducers(store.asyncReducers)

        store.replaceReducer(nextReducers)
      })
    })
  }

  return store
}
<|endoftext|>


<commit_before>var fs = require('fs');
var expect = require('chai').expect;
var stylus = require('stylus');

exports._compileCss = function (options) {
  // Strip out fonts that are not going to be tested
  var css = fs.readFileSync(options.cssFilepath, 'utf8');
  var fontFormat = options.fontFormat;
  var fontNames = options.fontNames || {};
  if (fontFormat !== 'eot') {
    var eotName = fontNames.eotName || 'font.eot';
    css = css.replace(new RegExp('\\s+src:url\\("' + eotName + '"\\);', 'g'), '');
    css = css.replace(new RegExp('\\s*url\\("' + eotName + '\\?#iefix"\\) format\\("embedded-opentype"\\),\\s*', 'g'), '');
    expect(css).to.not.contain(eotName);
  }
  if (fontFormat !== 'woff') {
    var woffName = fontNames.woffName || 'font.woff';
    console.log(woffName);
    css = css.replace(new RegExp('\\s*url\\(' + woffName + '"\\) format\\("woff"\\),\\s*', 'g'), '');
    expect(css).to.not.contain(woffName);
  }
  if (fontFormat !== 'ttf') {
    var ttfName = fontNames.ttfName || 'font.ttf';
    css = css.replace(new RegExp('\\s*url\\("' + ttfName + '"\\) format\\("truetype"\\),\\s*', 'g'), '');
    expect(css).to.not.contain(ttfName);
  }
  if (fontFormat !== 'svg') {
    // Guarantee no-commas for font formats
    var svgName = fontNames.svgName || 'font.svg';
    css = css.replace(',', ';');
    css = css.replace(new RegExp('\\s*url\\("' + svgName + '#icomoon"\\) format\\("svg"\\);\\s*/', 'g'), '');
    expect(css).to.not.contain(svgName);
  }

  // Replace font path with our font path
  // var fontFilepath = __dirname + '/actual_files/single/font.svg';
  var fontFilepath = options.fontFilepath;
  var fontname = fontNames[fontFormat + 'Name'] || 'font.' + fontFormat;
  // console.log(css);
  css = css.replace(fontname,  fontFilepath);

  // Assert our replacements were successful
  expect(css).to.contain(fontFilepath, '`compileCss` has not replaced "' + fontname + '" with "' + fontFilepath + '" successfully');

  // Return the css
  return css;
};

exports.compileStylus = function (options) {
  before(function compileStylusFn (done) {
    // Prepare the Stylus
    var baseStyl = exports._compileCss(options);

    // Render the stylus
    var charStyl = [
      '.icon-eye',
      '  icon($eye)',
      '.icon-building_block',
      '  icon($building_block)',
      '.icon-moon',
      '  icon($moon)'
    ].join('\n');
    var that = this;
    stylus.render(baseStyl + '\n' + charStyl, function (err, css) {
      // Save the CSS for later and callback
      that.css = css;
      done(err);
    });
  });
};
<commit_msg>Added assertion for commas<commit_after>var fs = require('fs');
var expect = require('chai').expect;
var stylus = require('stylus');

exports._compileCss = function (options) {
  // Strip out fonts that are not going to be tested
  var css = fs.readFileSync(options.cssFilepath, 'utf8');
  var fontFormat = options.fontFormat;
  var fontNames = options.fontNames || {};
  if (fontFormat !== 'eot') {
    var eotName = fontNames.eotName || 'font.eot';
    css = css.replace(new RegExp('\\s+src:url\\("' + eotName + '"\\);', 'g'), '');
    css = css.replace(new RegExp('\\s*url\\("' + eotName + '\\?#iefix"\\) format\\("embedded-opentype"\\),\\s*', 'g'), '');
    expect(css).to.not.contain(eotName);
  }
  if (fontFormat !== 'woff') {
    var woffName = fontNames.woffName || 'font.woff';
    console.log(woffName);
    css = css.replace(new RegExp('\\s*url\\(' + woffName + '"\\) format\\("woff"\\),\\s*', 'g'), '');
    expect(css).to.not.contain(woffName);
  }
  if (fontFormat !== 'ttf') {
    var ttfName = fontNames.ttfName || 'font.ttf';
    css = css.replace(new RegExp('\\s*url\\("' + ttfName + '"\\) format\\("truetype"\\),\\s*', 'g'), '');
    expect(css).to.not.contain(ttfName);
  }
  if (fontFormat !== 'svg') {
    // Guarantee no-commas for font formats
    var svgName = fontNames.svgName || 'font.svg';
    css = css.replace(',', ';');
    css = css.replace(new RegExp('\\s*url\\("' + svgName + '#icomoon"\\) format\\("svg"\\);\\s*/', 'g'), '');
    expect(css).to.not.contain(svgName);
  }

  // Replace font path with our font path
  // var fontFilepath = __dirname + '/actual_files/single/font.svg';
  var fontFilepath = options.fontFilepath;
  var fontname = fontNames[fontFormat + 'Name'] || 'font.' + fontFormat;
  // console.log(css);
  css = css.replace(fontname,  fontFilepath);

  // Assert our replacements were successful
  // TOOD: Should we assert commas are gone?
  // expect(css).to.not.contain(',');
  expect(css).to.contain(fontFilepath, '`compileCss` has not replaced "' + fontname + '" with "' + fontFilepath + '" successfully');

  // Return the css
  return css;
};

exports.compileStylus = function (options) {
  before(function compileStylusFn (done) {
    // Prepare the Stylus
    var baseStyl = exports._compileCss(options);

    // Render the stylus
    var charStyl = [
      '.icon-eye',
      '  icon($eye)',
      '.icon-building_block',
      '  icon($building_block)',
      '.icon-moon',
      '  icon($moon)'
    ].join('\n');
    var that = this;
    stylus.render(baseStyl + '\n' + charStyl, function (err, css) {
      // Save the CSS for later and callback
      that.css = css;
      done(err);
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

var test = require('tap').test;

var VContext = require('../lib/vcon.js');

test('VContext.create with empty args returns empty vCon', function (t) {
  t.deepEqual(VContext.create([], []).values, {}, 'should be empty object');
  t.deepEqual(VContext.create([], ['a']).values, {}, 'should be empty object');
  t.end();
});

test('VContext.create with more args than params, ignore extra args', function (t) {
  t.deepEqual(VContext.create([1], []).values, {}, 'should be empty object');
  t.deepEqual(VContext.create([1, 2], ['a']).values, { a: 1 },
              'should be object with one value');
  t.end();
});

test('VContext.create sets vCon[paramName] to arg value', function (t) {
  t.deepEqual(VContext.create([1, 2], ['a', 'b']).values, { a: 1, b: 2 },
              'should have all values');
  t.end();
});

test('create with locals is merged with args taking precedence', function (t) {
  var locals = { a: 11, c: 30 };
  t.deepEqual(VContext.create([1, 2], ['a', 'b'], locals).values,
              { a: 1, c: 30, b: 2 }, 'should have merge of values');
  t.end();
});

test('create with locals should not modify original locals', function (t) {
  var locals = { a: 11, c: 30 };
  t.deepEqual(VContext.create([1, 2], ['a', 'b'], locals).values,
              { a: 1, c: 30, b: 2 }, 'should have merge of values');
  t.deepEqual(locals, { a: 11, c: 30 }, 'should not modify original locals object');
  t.end();
});

test('getVar on null returns null', function (t) {
  t.equal(VContext.create([null], ['a']).getVar('a'), null);
  t.equal(VContext.create([{ b: null }], ['a']).getVar('a.b'), null);
  t.end();
});

test('getVar on undefined or null parent returns undefined', function (t) {
  t.equal(VContext.create([], []).getVar('a'), undefined);
  t.equal(VContext.create([], ['a']).getVar('a'), undefined);
  t.equal(VContext.create([], ['a']).getVar('a.b'), undefined);
  t.equal(VContext.create([], ['a']).getVar('a.b.c'), undefined);
  t.equal(VContext.create([null], ['a']).getVar('a.b'), undefined);
  t.equal(VContext.create([null], ['a']).getVar('a.b.c'), undefined);
  t.equal(VContext.create([1], ['a']).getVar('a.b'), undefined);
  t.equal(VContext.create([1], ['a']).getVar('a.b.c'), undefined);
  t.end();
});

test('simple getVar returns existing value', function (t) {
  t.equal(VContext.create([null], ['a']).getVar('a'), null);
  t.equal(VContext.create([1], ['a']).getVar('a'), 1);
  t.equal(VContext.create([true], ['a']).getVar('a'), true);
  t.equal(VContext.create(['banana'], ['a']).getVar('a'), 'banana');
  t.end();
});

test('getVar on literals returns the literal', function (t) {
  t.equal(VContext.create([], []).getVar(true), true);
  t.equal(VContext.create([], []).getVar(false), false);
  t.equal(VContext.create([], []).getVar(null), null);
  t.equal(VContext.create([], []).getVar('true'), true);
  t.equal(VContext.create([], []).getVar('false'), false);
  t.equal(VContext.create([], []).getVar('null'), null);
  t.equal(VContext.create([], []).getVar(-100), -100);
  t.equal(VContext.create([], []).getVar(100), 100);
  t.equal(VContext.create([], []).getVar(123.4), 123.4);
  t.equal(VContext.create([], []).getVar(-987.6), -987.6);
  t.equal(VContext.create([], []).getVar('-100'), -100);
  t.equal(VContext.create([], []).getVar('100'), 100);
  t.equal(VContext.create([], []).getVar('123.4'), 123.4);
  t.equal(VContext.create([], []).getVar('-987.6'), -987.6);
  t.equal(VContext.create([], []).getVar('"foo"'), 'foo');
  t.equal(VContext.create([], []).getVar("'foo'"), 'foo');
  t.equal(VContext.create([], []).getVar("'foo.bar'"), 'foo.bar');
  t.equal(VContext.create([], []).getVar("'foo-bar'"), 'foo-bar');
  t.deepEqual(VContext.create([], [], null, { a: 1}).getVar('this'), { a: 1});
  t.end();
});

test('getVar for property returns the property', function (t) {
  var o = { b: 100};
  t.equal(VContext.create([o], ['a']).getVar('a.b'), 100);
  o = { b: { c: 200 }};
  t.equal(VContext.create([o], ['a']).getVar('a.b.c'), 200);
  t.end();
});

test('setVar will create objects if needed', function (t) {
  var v = VContext.create([], []);
  v.setVar('foo.bar.baz', 100);
  t.deepEqual(v.values, { foo: { bar: { baz: 100}}});
  t.end();
});

test('simple setVar', function (t) {
  var v = VContext.create([], []);
  v.setVar('foo', 100);
  t.deepEqual(v.values, { foo: 100});
  t.end();
});

test('setVar will not affect other vars', function (t) {
  var v = VContext.create([{ bar: 1}], ['foo']);
  v.setVar('foo.baz', 2);
  t.deepEqual(v.values, { foo: { bar: 1, baz: 2 }});
  t.end();
});

test('setVar with null key, will not set anything', function (t) {
  var v = VContext.create([{ bar: 1}], ['foo']);
  v.setVar(null, 2);
  t.deepEqual(v.values, { foo: { bar: 1 }});
  t.end();
});

test('setVar with undefined key, will not set anything', function (t) {
  var v = VContext.create([{ bar: 1}], ['foo']);
  v.setVar(undefined, 2);
  t.deepEqual(v.values, { foo: { bar: 1 }});
  t.end();
});

test('saveResults will set values for params and :LAST_RESULTS', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', 'bar', 'cat'], [1, 'hello', null]);
  t.deepEqual(v.values, { foo: 1, bar: 'hello', cat: null ,
                          ':LAST_RESULTS': [1, 'hello', null] });
  t.end();
});

test('saveResults set :LAST_RESULT w/all even params is short', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo'], [1, 'hello', null]);
  t.deepEqual(v.values, { foo: 1,
                          ':LAST_RESULTS': [1, 'hello', null] });
  t.end();
});

test('saveResults will set values for params and :LAST_RESULTS', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', 'bar', 'cat'], [1, 'hello', null]);
  t.deepEqual(v.values, { foo: 1, bar: 'hello', cat: null ,
                          ':LAST_RESULTS': [1, 'hello', null] });
  t.end();
});

test('saveResults upgrades undefined to null, but :LAST_RESULT is exact', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', 'bar', 'baz'], [1, undefined]);
  t.deepEqual(v.values, { foo: 1, bar: null, baz: null,
                          ':LAST_RESULTS': [1, undefined] });
  t.end();
});

test('saveResults null params skips saving, :LAST_RESULT is exact', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', null], [1, 20]); //skip second param
  t.deepEqual(v.values, { foo: 1, ':LAST_RESULTS': [1, 20] });
  t.end();
});

<commit_msg>add dash and dot literal tests<commit_after>'use strict';

var test = require('tap').test;

var VContext = require('../lib/vcon.js');

test('VContext.create with empty args returns empty vCon', function (t) {
  t.deepEqual(VContext.create([], []).values, {}, 'should be empty object');
  t.deepEqual(VContext.create([], ['a']).values, {}, 'should be empty object');
  t.end();
});

test('VContext.create with more args than params, ignore extra args', function (t) {
  t.deepEqual(VContext.create([1], []).values, {}, 'should be empty object');
  t.deepEqual(VContext.create([1, 2], ['a']).values, { a: 1 },
              'should be object with one value');
  t.end();
});

test('VContext.create sets vCon[paramName] to arg value', function (t) {
  t.deepEqual(VContext.create([1, 2], ['a', 'b']).values, { a: 1, b: 2 },
              'should have all values');
  t.end();
});

test('create with locals is merged with args taking precedence', function (t) {
  var locals = { a: 11, c: 30 };
  t.deepEqual(VContext.create([1, 2], ['a', 'b'], locals).values,
              { a: 1, c: 30, b: 2 }, 'should have merge of values');
  t.end();
});

test('create with locals should not modify original locals', function (t) {
  var locals = { a: 11, c: 30 };
  t.deepEqual(VContext.create([1, 2], ['a', 'b'], locals).values,
              { a: 1, c: 30, b: 2 }, 'should have merge of values');
  t.deepEqual(locals, { a: 11, c: 30 }, 'should not modify original locals object');
  t.end();
});

test('getVar on null returns null', function (t) {
  t.equal(VContext.create([null], ['a']).getVar('a'), null);
  t.equal(VContext.create([{ b: null }], ['a']).getVar('a.b'), null);
  t.end();
});

test('getVar on undefined or null parent returns undefined', function (t) {
  t.equal(VContext.create([], []).getVar('a'), undefined);
  t.equal(VContext.create([], ['a']).getVar('a'), undefined);
  t.equal(VContext.create([], ['a']).getVar('a.b'), undefined);
  t.equal(VContext.create([], ['a']).getVar('a.b.c'), undefined);
  t.equal(VContext.create([null], ['a']).getVar('a.b'), undefined);
  t.equal(VContext.create([null], ['a']).getVar('a.b.c'), undefined);
  t.equal(VContext.create([1], ['a']).getVar('a.b'), undefined);
  t.equal(VContext.create([1], ['a']).getVar('a.b.c'), undefined);
  t.end();
});

test('simple getVar returns existing value', function (t) {
  t.equal(VContext.create([null], ['a']).getVar('a'), null);
  t.equal(VContext.create([1], ['a']).getVar('a'), 1);
  t.equal(VContext.create([true], ['a']).getVar('a'), true);
  t.equal(VContext.create(['banana'], ['a']).getVar('a'), 'banana');
  t.end();
});

test('getVar on literals returns the literal', function (t) {
  t.equal(VContext.create([], []).getVar(true), true);
  t.equal(VContext.create([], []).getVar(false), false);
  t.equal(VContext.create([], []).getVar(null), null);
  t.equal(VContext.create([], []).getVar('true'), true);
  t.equal(VContext.create([], []).getVar('false'), false);
  t.equal(VContext.create([], []).getVar('null'), null);
  t.equal(VContext.create([], []).getVar(-100), -100);
  t.equal(VContext.create([], []).getVar(100), 100);
  t.equal(VContext.create([], []).getVar(123.4), 123.4);
  t.equal(VContext.create([], []).getVar(-987.6), -987.6);
  t.equal(VContext.create([], []).getVar('-100'), -100);
  t.equal(VContext.create([], []).getVar('100'), 100);
  t.equal(VContext.create([], []).getVar('123.4'), 123.4);
  t.equal(VContext.create([], []).getVar('-987.6'), -987.6);
  t.equal(VContext.create([], []).getVar('"foo"'), 'foo');
  t.equal(VContext.create([], []).getVar("'foo'"), 'foo');
  t.equal(VContext.create([], []).getVar("'foo.bar'"), 'foo.bar');
  t.equal(VContext.create([], []).getVar("'foo-bar'"), 'foo-bar');
  t.equal(VContext.create([], []).getVar("'foo-bar.json'"), 'foo-bar.json');
  t.equal(VContext.create([], []).getVar('"foo-bar.json"'), 'foo-bar.json');
  t.deepEqual(VContext.create([], [], null, { a: 1}).getVar('this'), { a: 1});
  t.end();
});

test('getVar for property returns the property', function (t) {
  var o = { b: 100};
  t.equal(VContext.create([o], ['a']).getVar('a.b'), 100);
  o = { b: { c: 200 }};
  t.equal(VContext.create([o], ['a']).getVar('a.b.c'), 200);
  t.end();
});

test('setVar will create objects if needed', function (t) {
  var v = VContext.create([], []);
  v.setVar('foo.bar.baz', 100);
  t.deepEqual(v.values, { foo: { bar: { baz: 100}}});
  t.end();
});

test('simple setVar', function (t) {
  var v = VContext.create([], []);
  v.setVar('foo', 100);
  t.deepEqual(v.values, { foo: 100});
  t.end();
});

test('setVar will not affect other vars', function (t) {
  var v = VContext.create([{ bar: 1}], ['foo']);
  v.setVar('foo.baz', 2);
  t.deepEqual(v.values, { foo: { bar: 1, baz: 2 }});
  t.end();
});

test('setVar with null key, will not set anything', function (t) {
  var v = VContext.create([{ bar: 1}], ['foo']);
  v.setVar(null, 2);
  t.deepEqual(v.values, { foo: { bar: 1 }});
  t.end();
});

test('setVar with undefined key, will not set anything', function (t) {
  var v = VContext.create([{ bar: 1}], ['foo']);
  v.setVar(undefined, 2);
  t.deepEqual(v.values, { foo: { bar: 1 }});
  t.end();
});

test('saveResults will set values for params and :LAST_RESULTS', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', 'bar', 'cat'], [1, 'hello', null]);
  t.deepEqual(v.values, { foo: 1, bar: 'hello', cat: null ,
                          ':LAST_RESULTS': [1, 'hello', null] });
  t.end();
});

test('saveResults set :LAST_RESULT w/all even params is short', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo'], [1, 'hello', null]);
  t.deepEqual(v.values, { foo: 1,
                          ':LAST_RESULTS': [1, 'hello', null] });
  t.end();
});

test('saveResults will set values for params and :LAST_RESULTS', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', 'bar', 'cat'], [1, 'hello', null]);
  t.deepEqual(v.values, { foo: 1, bar: 'hello', cat: null ,
                          ':LAST_RESULTS': [1, 'hello', null] });
  t.end();
});

test('saveResults upgrades undefined to null, but :LAST_RESULT is exact', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', 'bar', 'baz'], [1, undefined]);
  t.deepEqual(v.values, { foo: 1, bar: null, baz: null,
                          ':LAST_RESULTS': [1, undefined] });
  t.end();
});

test('saveResults null params skips saving, :LAST_RESULT is exact', function (t) {
  var v = VContext.create([], []);
  v.saveResults(['foo', null], [1, 20]); //skip second param
  t.deepEqual(v.values, { foo: 1, ':LAST_RESULTS': [1, 20] });
  t.end();
});

<|endoftext|>


<commit_before>var game_state = {"place": "the_tavern",
                  "person": null,
                  "character": {"items": ["cat"]},
                 };

var message = "You are in a tavern. The local assassins hate you.";

function handle_take_action(resp) {
    if (resp.new_game) {
        location.reload();
    }
    document.getElementById("message").innerHTML = resp.message;
    document.getElementById("a").innerHTML = "a. " + resp.options["a"];
    if (resp.options["b"]) {
        document.getElementById("b").innerHTML = "b. " + resp.options["b"];
    } else {
        document.getElementById("b").innerHTML = "";
    }
    if (resp.options["c"]) {
        document.getElementById("c").innerHTML = "c. " + resp.options["c"];
    } else {
        document.getElementById("c").innerHTML = "";
    }
    if (resp.options["d"]) {
        document.getElementById("d").innerHTML = "d. " + resp.options["d"];
    } else {
        document.getElementById("d").innerHTML = "";
    }
    if (resp.options["e"] != "") {
        document.getElementById("e").innerHTML = "e. " + resp.options["e"];
    } else {
        document.getElementById("e").innerHTML = "";
    }
}

function main() {
    document.onkeypress = function(event) {
        switch (event.which) {
            case 65:
                console.log("you pressed A");
                break;
            case 97:
                console.log("you pressed a");
                $.post("take_action.json",
                       {"action": document.getElementById("a").innerHTML,
                        "game_state": game_state},
                       handle_take_action);
                break;
            case 66:
                console.log("you pressed B");
                break;
            case 98:
                console.log("you pressed b");
                break;
            case 67:
                console.log("you pressed C");
                break;
            case 99:
                console.log("you pressed c");
                break;
            case 68:
                console.log("you pressed D");
                break;
            case 100:
                console.log("you pressed d");
                break;
        }
    }
}

$(document).ready(main);
<commit_msg>cleaned up code, allowed numbers 1-5 to execute the options<commit_after>var game_state = {"place": "the tavern",
                  "person": null,
                  "character": {"items": ["cat"]},
                 };

var message = "You are in a tavern. The local assassins hate you.";

function handle_take_action(resp) {
    if (resp.new_game) {
        location.reload();
    }
    document.getElementById("message").innerHTML = resp.message;
    document.getElementById("a").innerHTML = "a. " + resp.options["a"];
    var letters = "bcde";
    var letter;
    for (index in letters) {
        letter = letters[index];
        if (resp.options[letter]) {
            document.getElementById(letter).innerHTML =
                letter + ". " + resp.options[letter];
        } else {
            document.getElementById(letter).innerHTML = "";
        }
    }
}

function call_post(letter) {
    $.post("take_action.json",
           {"action": document.getElementById(letter).innerHTML,
            "game_state": game_state},
           handle_take_action);
}

function main() {
    document.onkeypress = function(event) {
        var ascii = event.which;
        if (ascii == 49 || ascii == 65 || ascii == 97) {
            call_post("a");
        } else if (ascii == 50 || ascii == 66 || ascii == 98) {
            call_post("b");
        } else if (ascii == 51 || ascii == 67 || ascii == 99) {
            call_post("c");
        } else if (ascii == 52 || ascii == 68 || ascii == 100) {
            call_post("d");
        } else if (ascii == 53 || ascii == 69 || ascii == 101) {
            call_post("e");
        }
    }
}

$(document).ready(main);
<|endoftext|>


<commit_before>const expand     = require('../src/expand')
const concurrent = require('../src/concurrent')
const readFile   = require('../src/utils').readFile
const writeFile  = require('../src/utils').writeFile
const isOr       = require('../src/utils').isOr
const keys       = require('../src/utils').keys
const forEach    = require('../src/utils').forEach
const display    = require('./display')
const path       = require('path')
const assert     = require('assert')

function tmpls (opts, cb) {
  const license = opts.meta.license
  const tmpl = opts.files
  var files = []
  var filePath

  forEach(keys(tmpl), function (name) {
    if (tmpl[name]) {
      if (isOr(name, 'gitignore', 'eslintrc')) return files.push(name)
      if (isOr(name, 'index', 'test')) return files.push(name + '.js')
      if (name === 'package') return files.push(name + '.json')
      if (name === 'readme') return files.push(name.toUpperCase() + '.md')
      if (name === 'travis') return files.push(name + '.yml')
      if (name === 'license') {
        if (license === 'ISC') return files.push(name.toUpperCase() + '-ISC')
        else if (license === 'MIT') return files.push(name.toUpperCase() + '-MIT')
        else return files.push(name.toUpperCase() + '-UN')
      }
    }
  })

  display.heading('Templates')

  concurrent.each(files, function (file, key, next) {
    if (isOr(file, 'gitignore', 'travis.yml', 'eslintrc')) {
      filePath = './.' + file
    } else if (isOr(file, 'LICENSE-MIT', 'LICENSE-ISC', 'LICENSE-UN')) {
      filePath = './' + file.replace(/-(MIT|ISC|UN)/, '')
    } else {
      filePath = './' + file
    }

    processFile(filePath, file, opts, function () {
      next(null)
    })
  }, function (err, results) {
    assert.ifError(err)
    cb(null)
  })
}

function processFile (filePath, file, opts, done) {
  return readFile(path.join(__dirname, '../lib/' + file), function (err, res) {
    assert.ifError(err)
    var tmpl = expand(res, opts.meta)
    writeFile(filePath, tmpl, function (err) {
      assert.ifError(err)
      display.event('create:', file, 'white')
      done()
    })
  })
}

module.exports = tmpls
<commit_msg>refactor: app/tmpls -- redo the license section<commit_after>const expand     = require('../src/expand')
const concurrent = require('../src/concurrent')
const readFile   = require('../src/utils').readFile
const writeFile  = require('../src/utils').writeFile
const isOr       = require('../src/utils').isOr
const keys       = require('../src/utils').keys
const forEach    = require('../src/utils').forEach
const display    = require('./display')
const path       = require('path')
const assert     = require('assert')

function tmpls (opts, cb) {
  const license = opts.meta.license
  const tmpl = opts.files
  var files = []
  var filePath
  var lic

  forEach(keys(tmpl), function (name) {
    if (tmpl[name]) {
      if (isOr(name, 'gitignore', 'eslintrc')) return files.push(name)
      if (isOr(name, 'index', 'test')) return files.push(name + '.js')
      if (name === 'package') return files.push(name + '.json')
      if (name === 'readme') return files.push(name.toUpperCase() + '.md')
      if (name === 'travis') return files.push(name + '.yml')
    }
  })

  display.heading('Templates')

  concurrent.each(files, function (file, key, next) {
    if (isOr(file, 'gitignore', 'travis.yml', 'eslintrc')) {
      filePath = './.' + file
    } else {
      filePath = './' + file
    }

    processFile(filePath, '../lib/templates/', file, opts, function () {
      next(null)
    })
  }, function (err, results) {
    assert.ifError(err)
    if (license) lic = license.toLowerCase()
    else lic = 'no'

    processFile('./LICENSE', '../lib/license/', lic, opts, function () {
      cb(null)
    })
  })
}

function processFile (filePath, srcdir, file, opts, done) {
  return readFile(path.join(__dirname, srcdir + file), function (err, res) {
    assert.ifError(err)
    var tmpl = expand(res, opts.meta)
    writeFile(filePath, tmpl, function (err) {
      assert.ifError(err)
      if (srcdir === '../lib/license/') file = file.toUpperCase() + ' LICENSE'
      display.event('create:', file, 'white')
      done()
    })
  })
}

module.exports = tmpls
<|endoftext|>


<commit_before>'use strict';

var webpack = require('webpack');
var path = require('path');
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var NODE_ENV = process.env.NODE_ENV;

module.exports = {

    entry: {
        mainpage: './assets/scalajs-output-launcher.js'
    },
    output: {
        path: __dirname + '/assets',
        publicPath: "/assets/",
        filename: '[name]-bundle.js'
    },
    plugins: [
        new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('development'),
            }
        })
        //new CommonsChunkPlugin({
        //    name: "mainpage"
        //})
    ],
    //resolve: {
    //    alias: {
    //        react: path.resolve(__dirname + '/node_modules/react')
    //    }
    //},
    module: {
        loaders: [

            {
                test: /\.css\$/,
                loader: "style-loader!css-loader"
            },

            {
                test: /\.(png|jpg|svg)\$/,
                loaders: [
                    "url-loader?limit=8192",
                    "image-webpack?optimizationLevel=7&progressive=true"]
            } // inline base64 URLs for <=8k images, direct URLs for the rest
        ]
    }

};
<commit_msg>Update webpack.config.js<commit_after>'use strict';

var webpack = require('webpack');
var path = require('path');
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var NODE_ENV = process.env.NODE_ENV;

module.exports = {

    entry: {
        mainpage: './assets/scalajs-output-launcher.js'
    },
    output: {
        path: __dirname + '/assets',
        publicPath: "/assets/",
        filename: '[name]-bundle.js'
    },
    plugins: [
        new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('development'),
            }
        })
    ],

    module: {
        loaders: [

            {
                test: /\.css\$/,
                loader: "style-loader!css-loader"
            },

            {
                test: /\.(png|jpg|svg)\$/,
                loaders: [
                    "url-loader?limit=8192",
                    "image-webpack?optimizationLevel=7&progressive=true"]
            } // inline base64 URLs for <=8k images, direct URLs for the rest
        ]
    }

};
<|endoftext|>