<commit_before>// Cleaner.js - in api/services

const _ = require('lodash');

"use strict";

module.exports = {
    cleanDocumentCopies,
    cleanInstituteCopies,
    cleanSourceCopies
};

async function cleanInstituteCopies() {
    function getInstituteCopy(i) {
        return Institute.findOne({id: {'!': i.id}, scopusId: i.scopusId });
    }
    // bad hack: Institute 1 is the main institute
    const institutes = await Institute.find({id: {'!': 1}});
    const deletedInstitutes = [];
    for (let institute of institutes) {
        const copy = await getInstituteCopy(institute);
        if (!copy)
            continue;

        const affiliations = await Affiliation.find({institute: institute.id});
        const affiliationsIds = affiliations.map(a => a.id);
        const updateAffiliations = await Affiliation.update({id: affiliationsIds}, {institute: copy.id});
        await institute.destroy();
        deletedInstitutes.push(institute);
        sails.log.debug(`${updateAffiliations.length} affiliations updated from institute ${institute.id} to ${copy.id}`);
    }
    sails.log.debug(`${deletedInstitutes.length} deleted`);
}

async function cleanSourceCopies() {
    function getSourceCopy(i) {
        return Source.findOne({id: {'!': i.id}, scopusId: i.scopusId });
    }
    const sources = await Source.find();
    const deletedSources = [];
    for (let source of sources) {
        const copy = await getSourceCopy(source);
        if (!copy)
            continue;

        const documents = await Document.find({source: source.id});
        const documentIds = documents.map(d => d.id);
        const updateDocuments = await Document.update({id: documentIds}, {source: copy.id});
        await source.destroy();
        deletedSources.push(source);
        sails.log.debug(`${updateDocuments.length} documents updated from source ${source.id} to ${copy.id}`);
    }
    sails.log.debug(`${deletedSources.length} deleted`);
}

async function cleanDocumentCopies() {
    const mergedDocuments = [];
    const nonMergedDocuments = [];
    const documents = await Document.findByKind(DocumentKinds.VERIFIED);
    sails.log.debug(`${documents.length} documents to check found`);

    for (let partialDoc of documents) {
        const doc = await Document.findOneById(partialDoc.id)
            .populate('authors')
            .populate('groups')
            .populate('authorships')
            .populate('groupAuthorships')
            .populate('affiliations')
            .populate('discardedCoauthors')
            .populate('discardedGroups')
            .populate('discarded')
            .populate('discardedG');
        if (Document.getNumberOfConnections(doc) == 0) {
            sails.log.warn(`Document with id ${doc.id} is a verified document but has no connections`);
            continue;
        }
        const errors = [];
        const copies = await Document.findCopies(doc);
        if (copies.length == 0)
            continue;
        const copy = copies[0];
        for (let d of doc.discarded) {
            sails.log.debug(`User ${d.researchEntity} is removing ${doc.id} from the discarded`);
            const res = await User.undiscardDocument(User, d.researchEntity, d.document);
            if (res.error) {
                errors.push(res);
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`User ${d.researchEntity} is discarding ${copy.id}`);
                await User.discardDocument(User, d.researchEntity, copy.id);
            }
        }
        for (let d of doc.discardedG) {
            sails.log.debug(`Group ${d.researchEntity} is removing ${doc.id} from the discarded`);
            const res = await Group.undiscardDocument(Group, d.researchEntity, d.document);
            if (res.error) {
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`Group ${d.researchEntity} is discarding ${copy.id}`);
                await Group.discardDocument(Group, d.researchEntity, copy.id);
            }
        }
        for (let a of doc.authorships) {
            if (!a.researchEntity)
                continue;
            const instituteIds = doc.affiliations.filter(aff => aff.authorship == a.id).map(aff => aff.institute);
            sails.log.debug(`User ${a.researchEntity} is trying to verify document ${copy.id} (${copy.title}) in position: ${a.position}`);
            const res = await User.verifyDocument(User, a.researchEntity, copy.id, a.position, instituteIds, a.corresponding);
            if (res.error) {
                errors.push(res);
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`User ${a.researchEntity} is trying to unverify document ${doc.id} (${doc.title})`);
                await User.unverifyDocument(User, a.researchEntity, doc.id);
            }
        }
        for (let a of doc.groupAuthorships) {
            if (!a.researchEntity)
                continue;
            sails.log.debug(`Group ${a.researchEntity} is trying to verify document ${copy.id} (${copy.title})`);
            const res = await Group.verifyDocument(Group, a.researchEntity, copy.id, null, null, null);
            if (res.error) {
                errors.push(res);
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`Group ${a.researchEntity} is trying to unverify document ${doc.id} (${doc.title})`);
                await Group.unverifyDocument(Group, a.researchEntity, doc.id);
            }
        }
        if (errors.length) {
            sails.log.debug(`Document ${doc.id} should have been merged with  ${copy.id} but an error occured`)
            nonMergedDocuments.push({doc: doc, copy: copy});
        }
        else {
            sails.log.debug(`Document ${doc.id} was merged with ${copy.id}`);
            mergedDocuments.push({doc: doc, copy: copy});
        }
    }
    sails.log.debug(`${mergedDocuments.length} documents merged`);
    sails.log.debug(`${nonMergedDocuments.length} documents were not merged because of some error`);
}<commit_msg>Improved the cleaning service.<commit_after>// Cleaner.js - in api/services

const _ = require('lodash');

"use strict";

module.exports = {
    cleanDocumentCopies,
    cleanInstituteCopies,
    cleanSourceCopies
};

async function cleanInstituteCopies() {
    function getInstituteCopy(i) {
        return Institute.findOne({id: {'!': i.id}, scopusId: i.scopusId });
    }
    // bad hack: Institute 1 is the main institute
    const institutes = await Institute.find({id: {'!': 1}});
    const deletedInstitutes = [];
    for (let institute of institutes) {
        if (!institute.scopusId)
            continue;
        const copy = await getInstituteCopy(institute);
        if (!copy)
            continue;

        const affiliations = await Affiliation.find({institute: institute.id});
        if (affiliations.length) {
            const affiliationsIds = affiliations.map(a => a.id);
            const updateAffiliations = await Affiliation.update({id: affiliationsIds}, {institute: copy.id});
            sails.log.debug(`${updateAffiliations.length} affiliations updated from institute ${institute.id} to ${copy.id}`);
        }
        await institute.destroy();
        deletedInstitutes.push(institute);
    }
    sails.log.debug(`${deletedInstitutes.length} deleted`);
}

async function cleanSourceCopies() {
    function getSourceCopy(i) {
        return Source.findOne({id: {'!': i.id}, scopusId: i.scopusId });
    }
    const sources = await Source.find();
    const deletedSources = [];
    for (let source of sources) {
        if (!source.scopusId)
            continue;
        const copy = await getSourceCopy(source);
        if (!copy)
            continue;

        const documents = await Document.find({source: source.id});
        if (documents.length) {
            const documentIds = documents.map(d => d.id);
            const updateDocuments = await Document.update({id: documentIds}, {source: copy.id});
            sails.log.debug(`${updateDocuments.length} documents updated from source ${source.id} to ${copy.id}`);
        }
        await source.destroy();
        deletedSources.push(source);
    }
    sails.log.debug(`${deletedSources.length} deleted`);
}

async function cleanDocumentCopies() {
    const mergedDocuments = [];
    const nonMergedDocuments = [];
    const documents = await Document.findByKind(DocumentKinds.VERIFIED);
    sails.log.debug(`${documents.length} documents to check found`);

    for (let partialDoc of documents) {
        const doc = await Document.findOneById(partialDoc.id)
            .populate('authors')
            .populate('groups')
            .populate('authorships')
            .populate('groupAuthorships')
            .populate('affiliations')
            .populate('discardedCoauthors')
            .populate('discardedGroups')
            .populate('discarded')
            .populate('discardedG');
        if (Document.getNumberOfConnections(doc) == 0) {
            sails.log.warn(`Document with id ${doc.id} is a verified document but has no connections`);
            continue;
        }
        const errors = [];
        const copies = await Document.findCopies(doc);
        if (copies.length == 0)
            continue;
        const copy = copies[0];
        for (let d of doc.discarded) {
            sails.log.debug(`User ${d.researchEntity} is removing ${doc.id} from the discarded`);
            const res = await User.undiscardDocument(User, d.researchEntity, d.document);
            if (res.error) {
                errors.push(res);
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`User ${d.researchEntity} is discarding ${copy.id}`);
                await User.discardDocument(User, d.researchEntity, copy.id);
            }
        }
        for (let d of doc.discardedG) {
            sails.log.debug(`Group ${d.researchEntity} is removing ${doc.id} from the discarded`);
            const res = await Group.undiscardDocument(Group, d.researchEntity, d.document);
            if (res.error) {
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`Group ${d.researchEntity} is discarding ${copy.id}`);
                await Group.discardDocument(Group, d.researchEntity, copy.id);
            }
        }
        for (let a of doc.authorships) {
            if (!a.researchEntity)
                continue;
            const instituteIds = doc.affiliations.filter(aff => aff.authorship == a.id).map(aff => aff.institute);
            sails.log.debug(`User ${a.researchEntity} is trying to verify document ${copy.id} (${copy.title}) in position: ${a.position}`);
            const res = await User.verifyDocument(User, a.researchEntity, copy.id, a.position, instituteIds, a.corresponding);
            if (res.error) {
                errors.push(res);
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`User ${a.researchEntity} is trying to unverify document ${doc.id} (${doc.title})`);
                await User.unverifyDocument(User, a.researchEntity, doc.id);
            }
        }
        for (let a of doc.groupAuthorships) {
            if (!a.researchEntity)
                continue;
            sails.log.debug(`Group ${a.researchEntity} is trying to verify document ${copy.id} (${copy.title})`);
            const res = await Group.verifyDocument(Group, a.researchEntity, copy.id, null, null, null);
            if (res.error) {
                errors.push(res);
                sails.log.warn('Error: ');
                sails.log.warn(res.error);
            } else {
                sails.log.debug(`Group ${a.researchEntity} is trying to unverify document ${doc.id} (${doc.title})`);
                await Group.unverifyDocument(Group, a.researchEntity, doc.id);
            }
        }
        if (errors.length) {
            sails.log.debug(`Document ${doc.id} should have been merged with  ${copy.id} but an error occured`)
            nonMergedDocuments.push({doc: doc, copy: copy});
        }
        else {
            sails.log.debug(`Document ${doc.id} was merged with ${copy.id}`);
            mergedDocuments.push({doc: doc, copy: copy});
        }
    }
    sails.log.debug(`${mergedDocuments.length} documents merged`);
    sails.log.debug(`${nonMergedDocuments.length} documents were not merged because of some error`);
}<|endoftext|>


<commit_before>/* ==================================================================
 AngularJS Datatype Editor - List
 A directive to pick a new value from a list of values

 Usage:

{{data}}

 Config:
 "id" will be used in messages broadcast to the app on state changes.

 Messages:
 name: ADE-start
 data: id from config

 name: ADE-finish
 data: {id from config, old value, new value, exit value}

 ------------------------------------------------------------------*/
adeModule.directive('adeList', ['ADE', '$compile', '$rootScope', function(ADE, $compile, $rootScope) {
	return {
		require: '?ngModel', //optional dependency for ngModel
		restrict: 'A', //Attribute declaration eg:

		//The link step (after compile)
		link: function($scope, element, attrs, controller) {
			var options = {}; //The passed in options to the directive.
			var editing = false; //are we in edit mode or not
			var input = null; //a reference to the input DOM object
			var value = "";
			var oldValue = "";
			var exit = 0; //0=click, 1=tab, -1= shift tab, 2=return, -2=shift return, 3=esc. controls if you exited the field so you can focus the next field if appropriate

			//whenever the model changes, we get called so we can update our value
			if (controller) {
				controller.$render = function() {
					oldValue = value = controller.$modelValue;
					if (value == undefined || value == null) value = "";
					return controller.$viewValue;
				};
			}

			//called once the edit is done, so we can save the new data and remove edit mode
			var saveEdit = function(exited) {
				oldValue = value;
				exit = exited;

                console.log("saveEdit");
				if (exited != 3) { //don't save value on esc
					value = input.data().select2.data();
					var v="";
					if (angular.isArray(value) && value.length > 0) {

						angular.forEach(value, function(val, key) {
							val = (key < value.length-1) ? val.text +"," : val.text;
							v += val;
						});
						value = v;
					} else if (angular.isObject(value) && value.text !== "") {
						value = value.text;
					} else {
						value = (value) ? value.text : "";
					}

					controller.$setViewValue(value);
				}

                if (exited !== 0) {
                    if (v) element[0].innerHTML = v;
                    element.show();
                    input.select2('destroy'); //TODO: resolve console error when destroying this the second time for the same input
                    input.remove();
                    editing = false;
                } else if (exited == 0) {
                    setTimeout(function() {
                        input.select2('open');
                    });
                }

				ADE.done(options, oldValue, value, exit);

				if (!$scope.$$phase) {
					return $scope.$apply(); //This is necessary to get the model to match the value of the input
				}
			};

            $("body").bind("keyup", function(e) {
                $(document).find("div.select2-drop-active").each(function () {
                    if (e.keyCode == 27) { //esc
                        e.preventDefault();
                        e.stopPropagation();
                        var activeContainer = $(document).find('.select2-container-active');
                        var activeInput = activeContainer.next();
                        activeContainer.remove();
                        activeInput.remove();
                        element.show();
                        editing=false;
                    }
                });
            });

			//handles clicks on the read version of the data
			element.bind('click', function() {
				if (editing) return;
				editing = true;
				exit = 0;

				ADE.begin(options);
				element.hide();

				var multi = '';
				var placeholder = '';

				if (options.multiple) {
					multi = 'multiple="multiple"';
				} else {
					placeholder = ',placeholder:\'List...\'';
				}

				var query = '';
				if(options.query) query = ",query:" + options.query; //the user's query function for providing the list data
				var passthru = '';
				if(options.passthru) passthru = ",passthru:'" + options.passthru + "'"; //data that is passed through to the query function

				$compile('<input type="hidden" ui-select2={width:\'resolve\',allowClear:true,openOnEnter:false,allowAddNewValues:true'+query+passthru+',initSelection:selection'+placeholder+'} ' + multi + ' />')($scope)
					.insertAfter(element);
				input = element.next('input');

				var data = [], stringData=value;
				var cleanValue = (value) ? value.split(',') : [];

				angular.forEach(cleanValue, function(value, key) {
					$scope.listOptions.map(function(v,i) {
						if (value === v) {
							data.push({'id':i,'text':v });
						}
					});
				});

				if (!options.multiple) data = data[0];

				setTimeout(function() {
					input.select2("data", data);
					input.select2("open");
				});

				input.on("change", function(e) {
					if (!options.multiple) {
                        saveEdit();
                    } else {
                        console.log("calling saveEdit");
                        saveEdit(0);
                    }
				});

				//make sure we aren't already digesting/applying before we apply the changes
				if (!$scope.$$phase) {
					return $scope.$apply(); //This is necessary to get the model to match the value of the input
				}
			});

			// Watches for changes to the element
			// TODO: understand why I have to return the observer and why the observer returns element
			return attrs.$observe('adeList', function(settings) { //settings is the contents of the ade-list="" string
				options = ADE.parseSettings(settings, {
					multiple: false
				});
				return element;
			});
		}
	};
}]);

// Taken from Angular-UI and modified for our uses
// https://github.com/angular-ui/angular-ui
adeModule.directive('uiSelect2', ['$http', function($http) {
	var options = {};

	return {
		require: '?ngModel',
		compile: function(tElm, tAttrs) {
			var watch,
				repeatOption,
				repeatAttr,
				isSelect = tElm.is('select'),
				isMultiple = (tAttrs.multiple !== undefined);

			return function(scope, elm, attrs, controller) {
				// instance-specific options
				var opts = angular.extend({}, options, scope.$eval(attrs.uiSelect2));

				if (isMultiple) {
					opts.multiple = true;
				}

				if (controller) {
					// Watch the model for programmatic changes
					controller.$render = function() {
						if (isMultiple && !controller.$modelValue) {
							elm.select2('data', []);
						} else if (angular.isObject(controller.$modelValue)) {
							elm.select2('data', controller.$modelValue);
						} else {
							elm.select2('val', controller.$modelValue);
						}
					};

					// Watch the options dataset for changes
					if (watch) {
						scope.$watch(watch, function(newVal, oldVal, scope) {
							if (!newVal) return;
							// Delayed so that the options have time to be rendered
							setTimeout(function() {
								elm.select2('val', controller.$viewValue);
								// Refresh angular to remove the superfluous option
								elm.trigger('change');
							});
						});
					}

					if (!isSelect) {
						// Set the view and model value and update the angular template manually for the ajax/multiple select2.
						elm.bind("change", function() {
							scope.$apply(function() {
								controller.$setViewValue(elm.select2('data'));
							});
						});

						if (opts.initSelection) {
							var initSelection = opts.initSelection;
							opts.initSelection = function(element, callback) {
								initSelection(element, function(value) {
									controller.$setViewValue(value);
									callback(value);
								});
							};
						}
					}
				}

				attrs.$observe('disabled', function(value) {
					elm.select2(value && 'disable' || 'enable');
				});

				if (attrs.ngMultiple) {
					scope.$watch(attrs.ngMultiple, function(newVal) {
						elm.select2(opts);
					});
				}

				// Set initial value since Angular doesn't
				elm.val(scope.$eval(attrs.ngModel));

				// Initialize the plugin late so that the injected DOM does not disrupt the template compiler
				setTimeout(function() {
					elm.select2(opts);
				});
			};
		}
	};
}]);<commit_msg>Issue #25: added closeOnSelect option<commit_after>/* ==================================================================
 AngularJS Datatype Editor - List
 A directive to pick a new value from a list of values

 Usage:

{{data}}

 Config:
 "id" will be used in messages broadcast to the app on state changes.

 Messages:
 name: ADE-start
 data: id from config

 name: ADE-finish
 data: {id from config, old value, new value, exit value}

 ------------------------------------------------------------------*/
adeModule.directive('adeList', ['ADE', '$compile', '$rootScope', function(ADE, $compile, $rootScope) {
	return {
		require: '?ngModel', //optional dependency for ngModel
		restrict: 'A', //Attribute declaration eg:

		//The link step (after compile)
		link: function($scope, element, attrs, controller) {
			var options = {}; //The passed in options to the directive.
			var editing = false; //are we in edit mode or not
			var input = null; //a reference to the input DOM object
			var value = "";
			var oldValue = "";
			var exit = 0; //0=click, 1=tab, -1= shift tab, 2=return, -2=shift return, 3=esc. controls if you exited the field so you can focus the next field if appropriate

			//whenever the model changes, we get called so we can update our value
			if (controller) {
				controller.$render = function() {
					oldValue = value = controller.$modelValue;
					if (value == undefined || value == null) value = "";
					return controller.$viewValue;
				};
			}

			//called once the edit is done, so we can save the new data and remove edit mode
			var saveEdit = function(exited) {
				oldValue = value;
				exit = exited;

				if (exited != 3) { //don't save value on esc
					value = input.data().select2.data();
					var v="";
					if (angular.isArray(value) && value.length > 0) {

						angular.forEach(value, function(val, key) {
							val = (key < value.length-1) ? val.text +"," : val.text;
							v += val;
						});
						value = v;
					} else if (angular.isObject(value) && value.text !== "") {
						value = value.text;
					} else {
						value = (value) ? value.text : "";
					}

					controller.$setViewValue(value);
				}

                if (exited !== 0) {
                    if (v) element[0].innerHTML = v;
                    element.show();
                    input.select2('destroy'); //TODO: resolve console error when destroying this the second time for the same input
                    input.remove();
                    editing = false;
                }

				ADE.done(options, oldValue, value, exit);

				if (!$scope.$$phase) {
					return $scope.$apply(); //This is necessary to get the model to match the value of the input
				}
			};

            $("body").bind("keyup", function(e) {
                $(document).find("div.select2-drop-active").each(function () {
                    if (e.keyCode == 27) { //esc
                        e.preventDefault();
                        e.stopPropagation();
                        var activeContainer = $(document).find('.select2-container-active');
                        var activeInput = activeContainer.next();
                        activeContainer.remove();
                        activeInput.remove();
                        element.show();
                        editing=false;
                    }
                });
            });

			//handles clicks on the read version of the data
			element.bind('click', function() {
				if (editing) return;
				editing = true;
				exit = 0;

				ADE.begin(options);
				element.hide();

				var multi = '';
				var placeholder = '';

				if (options.multiple) {
					multi = 'multiple="multiple"';
				} else {
					placeholder = ',placeholder:\'List...\'';
				}

				var query = '';
				if(options.query) query = ",query:" + options.query; //the user's query function for providing the list data
				var passthru = '';
				if(options.passthru) passthru = ",passthru:'" + options.passthru + "'"; //data that is passed through to the query function

				$compile('<input type="hidden" ui-select2={width:\'resolve\',allowClear:true,openOnEnter:false,closeOnSelect:false,allowAddNewValues:true'+query+passthru+',initSelection:selection'+placeholder+'} ' + multi + ' />')($scope)
					.insertAfter(element);
				input = element.next('input');

				var data = [], stringData=value;
				var cleanValue = (value) ? value.split(',') : [];

				angular.forEach(cleanValue, function(value, key) {
					$scope.listOptions.map(function(v,i) {
						if (value === v) {
							data.push({'id':i,'text':v });
						}
					});
				});

				if (!options.multiple) data = data[0];

				setTimeout(function() {
					input.select2("data", data);
					input.select2("open");
				});

				input.on("change", function(e) {
					if (!options.multiple) {
                        saveEdit();
                    }
				});

                input.on("close", function(e) {
                   saveEdit();
                });

				//make sure we aren't already digesting/applying before we apply the changes
				if (!$scope.$$phase) {
					return $scope.$apply(); //This is necessary to get the model to match the value of the input
				}
			});

			// Watches for changes to the element
			// TODO: understand why I have to return the observer and why the observer returns element
			return attrs.$observe('adeList', function(settings) { //settings is the contents of the ade-list="" string
				options = ADE.parseSettings(settings, {
					multiple: false
				});
				return element;
			});
		}
	};
}]);

// Taken from Angular-UI and modified for our uses
// https://github.com/angular-ui/angular-ui
adeModule.directive('uiSelect2', ['$http', function($http) {
	var options = {};

	return {
		require: '?ngModel',
		compile: function(tElm, tAttrs) {
			var watch,
				repeatOption,
				repeatAttr,
				isSelect = tElm.is('select'),
				isMultiple = (tAttrs.multiple !== undefined);

			return function(scope, elm, attrs, controller) {
				// instance-specific options
				var opts = angular.extend({}, options, scope.$eval(attrs.uiSelect2));

				if (isMultiple) {
					opts.multiple = true;
				}

				if (controller) {
					// Watch the model for programmatic changes
					controller.$render = function() {
						if (isMultiple && !controller.$modelValue) {
							elm.select2('data', []);
						} else if (angular.isObject(controller.$modelValue)) {
							elm.select2('data', controller.$modelValue);
						} else {
							elm.select2('val', controller.$modelValue);
						}
					};

					// Watch the options dataset for changes
					if (watch) {
						scope.$watch(watch, function(newVal, oldVal, scope) {
							if (!newVal) return;
							// Delayed so that the options have time to be rendered
							setTimeout(function() {
								elm.select2('val', controller.$viewValue);
								// Refresh angular to remove the superfluous option
								elm.trigger('change');
							});
						});
					}

					if (!isSelect) {
						// Set the view and model value and update the angular template manually for the ajax/multiple select2.
						elm.bind("change", function() {
							scope.$apply(function() {
								controller.$setViewValue(elm.select2('data'));
							});
						});

						if (opts.initSelection) {
							var initSelection = opts.initSelection;
							opts.initSelection = function(element, callback) {
								initSelection(element, function(value) {
									controller.$setViewValue(value);
									callback(value);
								});
							};
						}
					}
				}

				attrs.$observe('disabled', function(value) {
					elm.select2(value && 'disable' || 'enable');
				});

				if (attrs.ngMultiple) {
					scope.$watch(attrs.ngMultiple, function(newVal) {
						elm.select2(opts);
					});
				}

				// Set initial value since Angular doesn't
				elm.val(scope.$eval(attrs.ngModel));

				// Initialize the plugin late so that the injected DOM does not disrupt the template compiler
				setTimeout(function() {
					elm.select2(opts);
				});
			};
		}
	};
}]);<|endoftext|>


<commit_before>module.exports = function(mongoose) {
    var schema = new mongoose.Schema({
        text:String,
        app:{type:mongoose.Schema.Types.ObjectId,ref:"apps"},
        user:{type:mongoose.Schema.Types.ObjectId,ref:"users"},
        files:[{type:mongoose.Schema.Types.ObjectId,ref:"files"}]
    },{
        timestamps:true
    })
    schema.methods.toResponseObject = function(){
        var obj = this.toObject();
        obj.id = this._id;
        obj._id = undefined;
        obj.__v = undefined;
        if(this.user.toResponseObject) obj.user=this.user.toResponseObject();
        if(this.app && this.app.toResponseObject){
            obj.app=this.app.toResponseObject();
            delete obj.app.appKey;
            delete obj.app.appSecret;
        }
        obj.text_html = obj.text;
        obj.text_html = obj.text_html.split('&').join("&")
        obj.text_html = obj.text_html.split("<").join("<")
        obj.text_html = obj.text_html.split(">").join(">")
        // obj.text_html = obj.text_html.split('"').join(""")
        obj.text_html = obj.text_html.split("\n").join("
")
        obj.text_html = obj.text_html.replace(/(^| |　)@([A-Za-z0-9_]+)/g,'$1@$2');
        obj.text_html = obj.text_html.replace(/(https?:\/\/[a-zA-Z0-9-\.]+(:[0-9]+)?(\/?[a-zA-Z0-9-\._~\!#$&'\(\)\*\+,\/:;=\?@\[\]]*))/g,'$1');

        return obj;
    }
    return mongoose.model("posts",schema)
};
<commit_msg>postに添付されたファイルを返していいオブジェクトに<commit_after>module.exports = function(mongoose) {
    var schema = new mongoose.Schema({
        text:String,
        app:{type:mongoose.Schema.Types.ObjectId,ref:"apps"},
        user:{type:mongoose.Schema.Types.ObjectId,ref:"users"},
        files:[{type:mongoose.Schema.Types.ObjectId,ref:"files"}]
    },{
        timestamps:true
    })
    schema.methods.toResponseObject = function(){
        var obj = this.toObject();
        obj.id = this._id;
        obj._id = undefined;
        obj.__v = undefined;
        if(this.user.toResponseObject) obj.user=this.user.toResponseObject();
        if(this.app && this.app.toResponseObject){
            obj.app=this.app.toResponseObject();
            delete obj.app.appKey;
            delete obj.app.appSecret;
        }
        if(this.files && this.files.length){
            for(let i=0;i<this.files.length;i++){
                if(!this.files[i].toResponseObject) break;
                obj.files[i] = this.files[i].toResponseObject();
            }
        }
        obj.text_html = obj.text;
        obj.text_html = obj.text_html.split('&').join("&")
        obj.text_html = obj.text_html.split("<").join("<")
        obj.text_html = obj.text_html.split(">").join(">")
        // obj.text_html = obj.text_html.split('"').join(""")
        obj.text_html = obj.text_html.split("\n").join("
")
        obj.text_html = obj.text_html.replace(/(^| |　)@([A-Za-z0-9_]+)/g,'$1@$2');
        obj.text_html = obj.text_html.replace(/(https?:\/\/[a-zA-Z0-9-\.]+(:[0-9]+)?(\/?[a-zA-Z0-9-\._~\!#$&'\(\)\*\+,\/:;=\?@\[\]]*))/g,'$1');
        return obj;
    }
    return mongoose.model("posts",schema)
};
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Mirantis, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
**/
define(
[
    'views/common',
    'models',
    'text!templates/support/page.html'
],
function(commonViews, models, supportPageTemplate) {
    'use strict';

    var SupportPage = commonViews.Page.extend({
        navbarActiveElement: 'support',
        breadcrumbsPath: [['Home', '#'], 'Support'],
        title: 'Support',
        updateInterval: 2000,
        template: _.template(supportPageTemplate),
        events: {
            'click .download-logs:not(.disabled)': 'downloadLogs'
        },
        scheduleUpdate: function() {
            var task = this.logsPackageTasks.filterTasks({name: 'dump'});
            if (this.timeout) {
                this.timeout.clear();
            }
            if (_.isUndefined(task[0]) || task[0].get('progress') < 100 ) {
                this.registerDeferred(this.timeout = $.timeout(this.updateInterval).done(_.bind(this.update, this)));
            } else {
                if (task[0].get('status') == 'error') {
                    this.$('.download-logs-error').text(task[0].get('message'));
                    this.$('.download-logs-error').removeClass('hide');
                } else {

                    this.$('.donwload-logs-link').removeClass('hide');
                    this.$('.donwload-logs-link > a').attr('href', task[0].get('message'));
                }
                this.$('.genereate-logs').addClass('hide');
                this.$('.download-logs').removeClass('disabled');
            }
        },
        update: function() {
            this.registerDeferred(this.logsPackageTasks.fetch().always(_.bind(this.scheduleUpdate, this)));
        },
        downloadLogs: function() {
            var task = new models.LogsPackage();
            task.save({}, {method: 'PUT'});
            this.$('.download-logs').addClass('disabled');
            this.$('.donwload-logs-link').addClass('hide');
            this.$('.download-logs-error').addlass('hide');
            this.$('.genereate-logs').removeClass('hide');
            this.logsPackageTasks = new models.Tasks();
            this.logsPackageTasks.fetch();
            this.scheduleUpdate();
        },
        initialize: function(options) {
            _.defaults(this, options);
            this.model = new models.FuelKey();
            this.model.fetch();
            this.model.on('change', this.render, this);
        },
        render: function() {
            this.$el.html(this.template());
            return this;
        }
    });

    return SupportPage;
});
<commit_msg>Use findTask instead of filterTasks<commit_after>/*
 * Copyright 2013 Mirantis, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
**/
define(
[
    'views/common',
    'models',
    'text!templates/support/page.html'
],
function(commonViews, models, supportPageTemplate) {
    'use strict';

    var SupportPage = commonViews.Page.extend({
        navbarActiveElement: 'support',
        breadcrumbsPath: [['Home', '#'], 'Support'],
        title: 'Support',
        updateInterval: 2000,
        template: _.template(supportPageTemplate),
        events: {
            'click .download-logs:not(.disabled)': 'downloadLogs'
        },
        scheduleUpdate: function() {
            var task = this.logsPackageTasks.findTask({name: 'dump'});
            if (this.timeout) {
                this.timeout.clear();
            }
            if (_.isUndefined(task) || task.get('progress') < 100 ) {
                this.registerDeferred(this.timeout = $.timeout(this.updateInterval).done(_.bind(this.update, this)));
            } else {
                if (task.get('status') == 'error') {
                    this.$('.download-logs-error').text(task.get('message'));
                    this.$('.download-logs-error').removeClass('hide');
                } else {

                    this.$('.donwload-logs-link').removeClass('hide');
                    this.$('.donwload-logs-link > a').attr('href', task.get('message'));
                }
                this.$('.genereate-logs').addClass('hide');
                this.$('.download-logs').removeClass('disabled');
            }
        },
        update: function() {
            this.registerDeferred(this.logsPackageTasks.fetch().always(_.bind(this.scheduleUpdate, this)));
        },
        downloadLogs: function() {
            var task = new models.LogsPackage();
            task.save({}, {method: 'PUT'});
            this.$('.download-logs').addClass('disabled');
            this.$('.donwload-logs-link').addClass('hide');
            this.$('.download-logs-error').addlass('hide');
            this.$('.genereate-logs').removeClass('hide');
            this.logsPackageTasks = new models.Tasks();
            this.logsPackageTasks.fetch();
            this.scheduleUpdate();
        },
        initialize: function(options) {
            _.defaults(this, options);
            this.model = new models.FuelKey();
            this.model.fetch();
            this.model.on('change', this.render, this);
        },
        render: function() {
            this.$el.html(this.template());
            return this;
        }
    });

    return SupportPage;
});
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

var mongoose = require('./mongoose_app').mongoose,
  Schema = mongoose.Schema,
  ModelNodeModule = require('./modelNode'),
    ModelNode = ModelNodeModule.ModelNode,
  utilsModule = require('../misc/utils'),
    utilsIsValidModelPath = utilsModule.isValidModelPath,
    getUtilsTemplate = utilsModule.getTemplate,
    getModelPathNames = utilsModule.getModelPathNames,
  populateSubDocsUtil = require('./model_utils').populateSubDocs,
  AnswerModule = require('./answer'),
    answerPopulateOptions = AnswerModule.getSubDocPopulateOptions,
  UserModule = require('./user'),
    userPopulateOptions = UserModule.getSubDocPopulateOptions,
    userPopulateProjection = UserModule.getPopulateProjection,
  PersonModule = require('./person'),
    personPopulateOptions = PersonModule.getSubDocPopulateOptions,
  AddressModule = require('./addresses'),
    addressPopulateOptions = AddressModule.getSubDocPopulateOptions;

var schema = new Schema({
  available: {
    type: Boolean,
    default: false
  },
  dontCanvass: {
    type: Boolean,
    default: false
  },
  tryAgain: {
    type: Boolean,
    default: false
  },
  support: {
    type: Number,
    default: -1
  },
  date: {
    type: Date,
    default: Date.now
  },
  answers: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Answer'
  }],
  canvasser: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  voter: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Person'
  },
  address: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Address'
  }
}, {
  timestamps: true
});

// create a model using schema
var model = mongoose.model('CanvassResult', schema);

var modelNode = new ModelNode(model, { populateSubDocs: populateSubDocs });

var modelTree = modelNode.getTree();

/*
 * Generates a canvass result template object from the specified source
 * @param{object} source      - object with properties to extract
 * @param {string[]} exPaths  - array of other paths to exclude
 */
function getTemplate (source, exPaths) {
  // set defaults for arguments not passed
  if (!exPaths) {
    // exclude object ref fields by default
    exPaths = ['canvass', 'answers', 'canvasser', 'voter', 'address'];
  }
  return getUtilsTemplate(source, model, exPaths);
}

/**
 * Check if a path is valid for this model
 * @param {string} path       - path to check
 * @param {string[]} exPaths  - array of paths to exclude
 * @param {boolean} checkSub  - check sub documents flag
 * @returns false or ModelNode if valid path
 */
function isValidModelPath (path, exPaths, checkSub) {
  checkSub = checkSub || false;

  var modelNodes;
  if (checkSub) {
    modelNodes = modelTree;
  } else {
    modelNodes = modelNode;
  }
  return utilsIsValidModelPath(modelNodes, path, exPaths);
}

/**
 * Get the subdocument populate options
 * @returns an array of populate objects of the form:
 *  @param {string} path       - path to subdocument
 *  @param {string} model      - name of subdocument model
 *  @param {function} populate - function to populate subdocument
 */
function getSubDocPopulateOptions () {
  return [
    { path: 'answers', model: 'Answer', populate: answerPopulateOptions() },
    { path: 'canvasser', model: 'User', populate: userPopulateOptions(), select: userPopulateProjection() },
    { path: 'voter', model: 'Person', populate: personPopulateOptions() },
    { path: 'address', model: 'Address', populate: addressPopulateOptions() }
  ];
}

/**
 * Get the root of the ModelNode tree for this model
 * @returns {object} root of ModelNode tree
 */
function getModelNodeTree () {
  return modelNode;
}

/**
 * Populate the subdocuments in a result set
 * @param {Array} docs    - documents to populate
 * @param {function} next - next function
 */
function populateSubDocs (docs, next) {
  populateSubDocsUtil(model, docs, getSubDocPopulateOptions(), next);

}

module.exports = {
  schema: schema,
  model: model,
  getTemplate: getTemplate,
  isValidModelPath: isValidModelPath,
  getSubDocPopulateOptions: getSubDocPopulateOptions,
  getModelNodeTree: getModelNodeTree,
  populateSubDocs: populateSubDocs
};<commit_msg>Canvass result default value<commit_after>/*jslint node: true */
'use strict';

var mongoose = require('./mongoose_app').mongoose,
  Schema = mongoose.Schema,
  ModelNodeModule = require('./modelNode'),
    ModelNode = ModelNodeModule.ModelNode,
  utilsModule = require('../misc/utils'),
    utilsIsValidModelPath = utilsModule.isValidModelPath,
    getUtilsTemplate = utilsModule.getTemplate,
    getModelPathNames = utilsModule.getModelPathNames,
  populateSubDocsUtil = require('./model_utils').populateSubDocs,
  AnswerModule = require('./answer'),
    answerPopulateOptions = AnswerModule.getSubDocPopulateOptions,
  UserModule = require('./user'),
    userPopulateOptions = UserModule.getSubDocPopulateOptions,
    userPopulateProjection = UserModule.getPopulateProjection,
  PersonModule = require('./person'),
    personPopulateOptions = PersonModule.getSubDocPopulateOptions,
  AddressModule = require('./addresses'),
    addressPopulateOptions = AddressModule.getSubDocPopulateOptions;

var schema = new Schema({
  available: {
    type: Boolean,
    default: true
  },
  dontCanvass: {
    type: Boolean,
    default: false
  },
  tryAgain: {
    type: Boolean,
    default: false
  },
  support: {
    type: Number,
    default: -1
  },
  date: {
    type: Date,
    default: Date.now
  },
  answers: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Answer'
  }],
  canvasser: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  voter: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Person'
  },
  address: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Address'
  }
}, {
  timestamps: true
});

// create a model using schema
var model = mongoose.model('CanvassResult', schema);

var modelNode = new ModelNode(model, { populateSubDocs: populateSubDocs });

var modelTree = modelNode.getTree();

/*
 * Generates a canvass result template object from the specified source
 * @param{object} source      - object with properties to extract
 * @param {string[]} exPaths  - array of other paths to exclude
 */
function getTemplate (source, exPaths) {
  // set defaults for arguments not passed
  if (!exPaths) {
    // exclude object ref fields by default
    exPaths = ['canvass', 'answers', 'canvasser', 'voter', 'address'];
  }
  return getUtilsTemplate(source, model, exPaths);
}

/**
 * Check if a path is valid for this model
 * @param {string} path       - path to check
 * @param {string[]} exPaths  - array of paths to exclude
 * @param {boolean} checkSub  - check sub documents flag
 * @returns false or ModelNode if valid path
 */
function isValidModelPath (path, exPaths, checkSub) {
  checkSub = checkSub || false;

  var modelNodes;
  if (checkSub) {
    modelNodes = modelTree;
  } else {
    modelNodes = modelNode;
  }
  return utilsIsValidModelPath(modelNodes, path, exPaths);
}

/**
 * Get the subdocument populate options
 * @returns an array of populate objects of the form:
 *  @param {string} path       - path to subdocument
 *  @param {string} model      - name of subdocument model
 *  @param {function} populate - function to populate subdocument
 */
function getSubDocPopulateOptions () {
  return [
    { path: 'answers', model: 'Answer', populate: answerPopulateOptions() },
    { path: 'canvasser', model: 'User', populate: userPopulateOptions(), select: userPopulateProjection() },
    { path: 'voter', model: 'Person', populate: personPopulateOptions() },
    { path: 'address', model: 'Address', populate: addressPopulateOptions() }
  ];
}

/**
 * Get the root of the ModelNode tree for this model
 * @returns {object} root of ModelNode tree
 */
function getModelNodeTree () {
  return modelNode;
}

/**
 * Populate the subdocuments in a result set
 * @param {Array} docs    - documents to populate
 * @param {function} next - next function
 */
function populateSubDocs (docs, next) {
  populateSubDocsUtil(model, docs, getSubDocPopulateOptions(), next);

}

module.exports = {
  schema: schema,
  model: model,
  getTemplate: getTemplate,
  isValidModelPath: isValidModelPath,
  getSubDocPopulateOptions: getSubDocPopulateOptions,
  getModelNodeTree: getModelNodeTree,
  populateSubDocs: populateSubDocs
};<|endoftext|>


<commit_before>import color from 'color';
import PLColors from 'PLColors';

import { Platform, Dimensions, PixelRatio } from 'react-native';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
const platform = Platform.OS;
const platformStyle = undefined;

export default {
  platformStyle,
  platform,
    // AndroidRipple
  androidRipple: true,
  androidRippleColor: 'rgba(256, 256, 256, 0.3)',
  androidRippleColorDark: 'rgba(0, 0, 0, 0.15)',

    // Badge
  badgeBg: '#ED1727',
  badgeColor: '#fff',
    // New Variable
  badgePadding: (platform === 'ios') ? 3 : 0,

    // Button
  btnFontFamily: (platform === 'ios') ? 'System' : 'Roboto_medium',
  btnDisabledBg: '#b5b5b5',
  btnDisabledClr: '#f1f1f1',

    // CheckBox
  CheckboxRadius: (platform === 'ios') ? 13 : 0,
  CheckboxBorderWidth: (platform === 'ios') ? 1 : 2,
  CheckboxPaddingLeft: (platform === 'ios') ? 4 : 2,
  CheckboxPaddingBottom: (platform === 'ios') ? 0 : 5,
  CheckboxIconSize: (platform === 'ios') ? 21 : 14,
  CheckboxIconMarginTop: (platform === 'ios') ? undefined : 1,
  CheckboxFontSize: (platform === 'ios') ? (23 / 0.9) : 18,
  DefaultFontSize: 17,
  checkboxBgColor: '#039BE5',
  checkboxSize: 20,
  checkboxTickColor: '#fff',

  // Segment
  segmentBackgroundColor: (platform === 'ios') ? '#F8F8F8' : '#3F51B5',
  segmentActiveBackgroundColor: (platform === 'ios') ? '#007aff' : '#fff',
  segmentTextColor: (platform === 'ios') ? '#007aff' : '#fff',
  segmentActiveTextColor: (platform === 'ios') ? '#fff' : '#3F51B5',
  segmentBorderColor: (platform === 'ios') ? '#007aff' : '#fff',
  segmentBorderColorMain: (platform === 'ios') ? '#a7a6ab' : '#3F51B5',

    // New Variable
  get defaultTextColor() {
    return this.textColor;
  },

  get btnPrimaryBg() {
    return this.brandPrimary;
  },
  get btnPrimaryColor() {
    return this.inverseTextColor;
  },
  get btnInfoBg() {
    return this.brandInfo;
  },
  get btnInfoColor() {
    return this.inverseTextColor;
  },
  get btnSuccessBg() {
    return this.brandSuccess;
  },
  get btnSuccessColor() {
    return this.inverseTextColor;
  },
  get btnDangerBg() {
    return this.brandDanger;
  },
  get btnDangerColor() {
    return this.inverseTextColor;
  },
  get btnWarningBg() {
    return this.brandWarning;
  },
  get btnWarningColor() {
    return this.inverseTextColor;
  },
  get btnTextSize() {
    return (platform === 'ios') ? this.fontSizeBase * 1.1 :
        this.fontSizeBase - 1;
  },
  get btnTextSizeLarge() {
    return this.fontSizeBase * 1.5;
  },
  get btnTextSizeSmall() {
    return this.fontSizeBase * 0.8;
  },
  get borderRadiusLarge() {
    return this.fontSizeBase * 3.8;
  },

  buttonPadding: 2,

  get iconSizeLarge() {
    return this.iconFontSize * 1.5;
  },
  get iconSizeSmall() {
    return this.iconFontSize * 0.6;
  },

    // Card
  cardDefaultBg: '#fff',

      // Color
  brandPrimary: (platform === 'ios') ? '#007aff' : '#3F51B5',
  brandInfo: '#62B1F6',
  brandSuccess: '#5cb85c',
  brandDanger: '#d9534f',
  brandWarning: '#f0ad4e',
  brandSidebar: '#252932',

    // Font
  fontFamily: (platform === 'ios') ? 'System' : 'Roboto',
  fontSizeBase: 15,

  get fontSizeH1() {
    return this.fontSizeBase * 1.8;
  },
  get fontSizeH2() {
    return this.fontSizeBase * 1.6;
  },
  get fontSizeH3() {
    return this.fontSizeBase * 1.4;
  },

    // Footer
  footerHeight: 55,
  footerDefaultBg: (platform === 'ios') ? '#F8F8F8' : '#4179F7',

    // FooterTab
  tabBarTextColor: '#8694ab',
  tabBarTextSize: (platform === 'ios') ? 8 : 7,
  activeTab: (platform === 'ios') ? '#007aff' : '#fff',
  sTabBarActiveTextColor: '#007aff',
  tabBarActiveTextColor: PLColors.main,
  tabActiveBgColor: (platform === 'ios') ? '#cde1f9' : '#3F51B5',

    // Tab
  tabDefaultBg: (platform === 'ios') ? '#F8F8F8' : '#3F51B5',
  topTabBarTextColor: (platform === 'ios') ? '#6b6b6b' : '#b3c7f9',
  topTabBarActiveTextColor: (platform === 'ios') ? '#007aff' : '#fff',
  topTabActiveBgColor: (platform === 'ios') ? '#cde1f9' : undefined,
  topTabBarBorderColor: (platform === 'ios') ? '#a7a6ab' : '#fff',
  topTabBarActiveBorderColor: (platform === 'ios') ? '#007aff' : '#fff',

    // Header
  toolbarBtnColor: (platform === 'ios') ? '#007aff' : '#fff',
  toolbarDefaultBg: (platform === 'ios') ? '#F8F8F8' : '#3F51B5',
  toolbarHeight: (platform === 'ios') ? 64 : 56,
  toolbarIconSize: (platform === 'ios') ? 20 : 22,
  toolbarSearchIconSize: (platform === 'ios') ? 20 : 23,
  toolbarInputColor: (platform === 'ios') ? '#CECDD2' : '#fff',
  searchBarHeight: (platform === 'ios') ? 30 : 40,
  toolbarInverseBg: '#222',
  toolbarTextColor: (platform === 'ios') ? '#000' : '#fff',
  toolbarDefaultBorder: (platform === 'ios') ? '#a7a6ab' : '#3F51B5',
  iosStatusbar: (platform === 'ios') ? 'light-content' : 'light-content',
  get statusBarColor() {
    return color(this.toolbarDefaultBg).darken(0.2).hexString();
  },

    // Icon
  iconFamily: 'Ionicons',
  iconFontSize: (platform === 'ios') ? 30 : 28,
  iconMargin: 7,
  iconHeaderSize: (platform === 'ios') ? 33 : 24,

    // InputGroup
  inputFontSize: 17,
  inputBorderColor: '#D9D5DC',
  inputSuccessBorderColor: '#2b8339',
  inputErrorBorderColor: '#ed2f2f',

  get inputColor() {
    return this.textColor;
  },
  get inputColorPlaceholder() {
    return '#575757';
  },

  inputGroupMarginBottom: 10,
  inputHeightBase: 50,
  inputPaddingLeft: 5,

  get inputPaddingLeftIcon() {
    return this.inputPaddingLeft * 8;
  },

    // Line Height
  btnLineHeight: 19,
  lineHeightH1: 32,
  lineHeightH2: 27,
  lineHeightH3: 22,
  iconLineHeight: (platform === 'ios') ? 37 : 30,
  lineHeight: (platform === 'ios') ? 20 : 24,

    // List
  listBorderColor: '#c9c9c9',
  listDividerBg: '#f4f4f4',
  listItemHeight: 45,
  listBtnUnderlayColor: '#DDD',

    // Card
  cardBorderColor: '#ccc',

    // Changed Variable
  listItemPadding: (platform === 'ios') ? 10 : 12,

  listNoteColor: '#808080',
  listNoteSize: 13,

    // Progress Bar
  defaultProgressColor: '#E4202D',
  inverseProgressColor: '#1A191B',

    // Radio Button
  radioBtnSize: (platform === 'ios') ? 25 : 23,
  radioSelectedColorAndroid: '#3F51B5',

    // New Variable
  radioBtnLineHeight: (platform === 'ios') ? 29 : 24,

  radioColor: '#7e7e7e',

  get radioSelectedColor() {
    return color(this.radioColor).darken(0.2).hexString();
  },

    // Spinner
  defaultSpinnerColor: '#45D56E',
  inverseSpinnerColor: '#1A191B',

    // Tabs
  tabBgColor: '#F8F8F8',
  tabFontSize: 15,
  tabTextColor: '#222222',

    // Text
  textColor: '#000',
  inverseTextColor: '#fff',
  noteFontSize: 14,

    // Title
  titleFontfamily: (platform === 'ios') ? 'System' : 'Roboto_medium',
  titleFontSize: (platform === 'ios') ? 17 : 19,
  subTitleFontSize: (platform === 'ios') ? 12 : 14,
  subtitleColor: (platform === 'ios') ? '#8e8e93' : '#FFF',

    // New Variable
  titleFontColor: (platform === 'ios') ? '#000' : '#FFF',

    // Other
  borderRadiusBase: (platform === 'ios') ? 5 : 2,
  borderWidth: (1/PixelRatio.getPixelSizeForLayoutSize(1)),
  contentPadding: 10,

  get darkenHeader() {
    return color(this.tabBgColor).darken(0.03).hexString();
  },

  dropdownBg: '#000',
  dropdownLinkColor: '#414142',
  inputLineHeight: 24,
  jumbotronBg: '#C9C9CE',
  jumbotronPadding: 30,
  deviceWidth,
  deviceHeight,

    // New Variable
  inputGroupRoundedBorderRadius: 30,
};
<commit_msg>issue #7 - Android: update tab bar text size to 6<commit_after>import color from 'color';
import PLColors from 'PLColors';

import { Platform, Dimensions, PixelRatio } from 'react-native';

const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
const platform = Platform.OS;
const platformStyle = undefined;

export default {
  platformStyle,
  platform,
  // AndroidRipple
  androidRipple: true,
  androidRippleColor: 'rgba(256, 256, 256, 0.3)',
  androidRippleColorDark: 'rgba(0, 0, 0, 0.15)',

  // Badge
  badgeBg: '#ED1727',
  badgeColor: '#fff',
  // New Variable
  badgePadding: (platform === 'ios') ? 3 : 0,

  // Button
  btnFontFamily: (platform === 'ios') ? 'System' : 'Roboto_medium',
  btnDisabledBg: '#b5b5b5',
  btnDisabledClr: '#f1f1f1',

  // CheckBox
  CheckboxRadius: (platform === 'ios') ? 13 : 0,
  CheckboxBorderWidth: (platform === 'ios') ? 1 : 2,
  CheckboxPaddingLeft: (platform === 'ios') ? 4 : 2,
  CheckboxPaddingBottom: (platform === 'ios') ? 0 : 5,
  CheckboxIconSize: (platform === 'ios') ? 21 : 14,
  CheckboxIconMarginTop: (platform === 'ios') ? undefined : 1,
  CheckboxFontSize: (platform === 'ios') ? (23 / 0.9) : 18,
  DefaultFontSize: 17,
  checkboxBgColor: '#039BE5',
  checkboxSize: 20,
  checkboxTickColor: '#fff',

  // Segment
  segmentBackgroundColor: (platform === 'ios') ? '#F8F8F8' : '#3F51B5',
  segmentActiveBackgroundColor: (platform === 'ios') ? '#007aff' : '#fff',
  segmentTextColor: (platform === 'ios') ? '#007aff' : '#fff',
  segmentActiveTextColor: (platform === 'ios') ? '#fff' : '#3F51B5',
  segmentBorderColor: (platform === 'ios') ? '#007aff' : '#fff',
  segmentBorderColorMain: (platform === 'ios') ? '#a7a6ab' : '#3F51B5',

  // New Variable
  get defaultTextColor() {
    return this.textColor;
  },

  get btnPrimaryBg() {
    return this.brandPrimary;
  },
  get btnPrimaryColor() {
    return this.inverseTextColor;
  },
  get btnInfoBg() {
    return this.brandInfo;
  },
  get btnInfoColor() {
    return this.inverseTextColor;
  },
  get btnSuccessBg() {
    return this.brandSuccess;
  },
  get btnSuccessColor() {
    return this.inverseTextColor;
  },
  get btnDangerBg() {
    return this.brandDanger;
  },
  get btnDangerColor() {
    return this.inverseTextColor;
  },
  get btnWarningBg() {
    return this.brandWarning;
  },
  get btnWarningColor() {
    return this.inverseTextColor;
  },
  get btnTextSize() {
    return (platform === 'ios') ? this.fontSizeBase * 1.1 :
      this.fontSizeBase - 1;
  },
  get btnTextSizeLarge() {
    return this.fontSizeBase * 1.5;
  },
  get btnTextSizeSmall() {
    return this.fontSizeBase * 0.8;
  },
  get borderRadiusLarge() {
    return this.fontSizeBase * 3.8;
  },

  buttonPadding: 2,

  get iconSizeLarge() {
    return this.iconFontSize * 1.5;
  },
  get iconSizeSmall() {
    return this.iconFontSize * 0.6;
  },

  // Card
  cardDefaultBg: '#fff',

  // Color
  brandPrimary: (platform === 'ios') ? '#007aff' : '#3F51B5',
  brandInfo: '#62B1F6',
  brandSuccess: '#5cb85c',
  brandDanger: '#d9534f',
  brandWarning: '#f0ad4e',
  brandSidebar: '#252932',

  // Font
  fontFamily: (platform === 'ios') ? 'System' : 'Roboto',
  fontSizeBase: 15,

  get fontSizeH1() {
    return this.fontSizeBase * 1.8;
  },
  get fontSizeH2() {
    return this.fontSizeBase * 1.6;
  },
  get fontSizeH3() {
    return this.fontSizeBase * 1.4;
  },

  // Footer
  footerHeight: 55,
  footerDefaultBg: (platform === 'ios') ? '#F8F8F8' : '#4179F7',

  // FooterTab
  tabBarTextColor: '#8694ab',
  tabBarTextSize: (platform === 'ios') ? 8 : 6,
  activeTab: (platform === 'ios') ? '#007aff' : '#fff',
  sTabBarActiveTextColor: '#007aff',
  tabBarActiveTextColor: PLColors.main,
  tabActiveBgColor: (platform === 'ios') ? '#cde1f9' : '#3F51B5',

  // Tab
  tabDefaultBg: (platform === 'ios') ? '#F8F8F8' : '#3F51B5',
  topTabBarTextColor: (platform === 'ios') ? '#6b6b6b' : '#b3c7f9',
  topTabBarActiveTextColor: (platform === 'ios') ? '#007aff' : '#fff',
  topTabActiveBgColor: (platform === 'ios') ? '#cde1f9' : undefined,
  topTabBarBorderColor: (platform === 'ios') ? '#a7a6ab' : '#fff',
  topTabBarActiveBorderColor: (platform === 'ios') ? '#007aff' : '#fff',

  // Header
  toolbarBtnColor: (platform === 'ios') ? '#007aff' : '#fff',
  toolbarDefaultBg: (platform === 'ios') ? '#F8F8F8' : '#3F51B5',
  toolbarHeight: (platform === 'ios') ? 64 : 56,
  toolbarIconSize: (platform === 'ios') ? 20 : 22,
  toolbarSearchIconSize: (platform === 'ios') ? 20 : 23,
  toolbarInputColor: (platform === 'ios') ? '#CECDD2' : '#fff',
  searchBarHeight: (platform === 'ios') ? 30 : 40,
  toolbarInverseBg: '#222',
  toolbarTextColor: (platform === 'ios') ? '#000' : '#fff',
  toolbarDefaultBorder: (platform === 'ios') ? '#a7a6ab' : '#3F51B5',
  iosStatusbar: (platform === 'ios') ? 'light-content' : 'light-content',
  get statusBarColor() {
    return color(this.toolbarDefaultBg).darken(0.2).hexString();
  },

  // Icon
  iconFamily: 'Ionicons',
  iconFontSize: (platform === 'ios') ? 30 : 28,
  iconMargin: 7,
  iconHeaderSize: (platform === 'ios') ? 33 : 24,

  // InputGroup
  inputFontSize: 17,
  inputBorderColor: '#D9D5DC',
  inputSuccessBorderColor: '#2b8339',
  inputErrorBorderColor: '#ed2f2f',

  get inputColor() {
    return this.textColor;
  },
  get inputColorPlaceholder() {
    return '#575757';
  },

  inputGroupMarginBottom: 10,
  inputHeightBase: 50,
  inputPaddingLeft: 5,

  get inputPaddingLeftIcon() {
    return this.inputPaddingLeft * 8;
  },

  // Line Height
  btnLineHeight: 19,
  lineHeightH1: 32,
  lineHeightH2: 27,
  lineHeightH3: 22,
  iconLineHeight: (platform === 'ios') ? 37 : 30,
  lineHeight: (platform === 'ios') ? 20 : 24,

  // List
  listBorderColor: '#c9c9c9',
  listDividerBg: '#f4f4f4',
  listItemHeight: 45,
  listBtnUnderlayColor: '#DDD',

  // Card
  cardBorderColor: '#ccc',

  // Changed Variable
  listItemPadding: (platform === 'ios') ? 10 : 12,

  listNoteColor: '#808080',
  listNoteSize: 13,

  // Progress Bar
  defaultProgressColor: '#E4202D',
  inverseProgressColor: '#1A191B',

  // Radio Button
  radioBtnSize: (platform === 'ios') ? 25 : 23,
  radioSelectedColorAndroid: '#3F51B5',

  // New Variable
  radioBtnLineHeight: (platform === 'ios') ? 29 : 24,

  radioColor: '#7e7e7e',

  get radioSelectedColor() {
    return color(this.radioColor).darken(0.2).hexString();
  },

  // Spinner
  defaultSpinnerColor: '#45D56E',
  inverseSpinnerColor: '#1A191B',

  // Tabs
  tabBgColor: '#F8F8F8',
  tabFontSize: 15,
  tabTextColor: '#222222',

  // Text
  textColor: '#000',
  inverseTextColor: '#fff',
  noteFontSize: 14,

  // Title
  titleFontfamily: (platform === 'ios') ? 'System' : 'Roboto_medium',
  titleFontSize: (platform === 'ios') ? 17 : 19,
  subTitleFontSize: (platform === 'ios') ? 12 : 14,
  subtitleColor: (platform === 'ios') ? '#8e8e93' : '#FFF',

  // New Variable
  titleFontColor: (platform === 'ios') ? '#000' : '#FFF',

  // Other
  borderRadiusBase: (platform === 'ios') ? 5 : 2,
  borderWidth: (1 / PixelRatio.getPixelSizeForLayoutSize(1)),
  contentPadding: 10,

  get darkenHeader() {
    return color(this.tabBgColor).darken(0.03).hexString();
  },

  dropdownBg: '#000',
  dropdownLinkColor: '#414142',
  inputLineHeight: 24,
  jumbotronBg: '#C9C9CE',
  jumbotronPadding: 30,
  deviceWidth,
  deviceHeight,

  // New Variable
  inputGroupRoundedBorderRadius: 30,
};
<|endoftext|>


<commit_before>module.exports = SensorModel = Backbone.Model.extend({
    urlRoot: 'http://localhost:4000/sensor/',
    idAttribute: 'sensor_id',
    defaults : {
        name: 'MySensor',
        sensor_id: "",
        room: "",
    },
    schema: {
        name: 'Text',
        sensor_id: { editorAttrs: { disabled: true } },
        model: { type: 'Select', options: ['temperature', 'door'],  editorAttrs: { disabled: true }},
        room: {type: 'Select', options: function(){
            var options = [{val: 0, label:"Unassigned"}];
            $.getJSON(
                'http://localhost:4000/room/',
                function(rooms){
                    rooms.forEach(function(room){
                        options.push({ val: room['_id'], label: room['name'] });
                    });
                }
            );
            return options;
        }()},
    }
});
<commit_msg>Change room to room_id in sensor model<commit_after>module.exports = SensorModel = Backbone.Model.extend({
    urlRoot: 'http://localhost:4000/sensor/',
    idAttribute: 'sensor_id',
    defaults : {
        name: 'MySensor',
        sensor_id: "",
        room_id: "",
    },
    schema: {
        name: 'Text',
        sensor_id: { editorAttrs: { disabled: true } },
        model: { type: 'Select', options: ['temperature', 'door'],  editorAttrs: { disabled: true }},
        room_id: {type: 'Select', options: function(){
            var options = [{val: 0, label:"Unassigned"}];
            $.getJSON(
                'http://localhost:4000/room/',
                function(rooms){
                    rooms.forEach(function(room){
                        options.push({ val: room['_id'], label: room['name'] });
                    });
                }
            );
            return options;
        }()},
    }
});
<|endoftext|>


<commit_before>'use strict';

angular
    .module('filter-model', ['constants', 'api'])
    .factory('Filter', function($q, $angularCacheFactory, API, APPNAME, Session){

        return (function() {

            var promise;
            var selection;
            var sics, years, periods, entities, tags;

            function init(){
                if(promise === undefined) {
                    var deferred = $q.defer();

                    API.Report.getParameters({$method: 'POST'})
                        .then(
                            function (data) {
                                setSics(data.sics);
                                setEntities(data.entities);
                                setYears(data.years);
                                setPeriods(data.periods);
                                setTags(data.tags);
                                promise = undefined;
                                deferred.resolve(data);
                            },
                            function (e) {
                                promise = undefined;
                                deferred.reject(e);
                            }
                        );

                    promise = deferred.promise;
                }
                return promise;
            }

            function getSics(){
                var deferred = $q.defer();

                if(sics === undefined){
                    init()
                        .then(
                            function (data) {
                                setSics(data.sics);
                                deferred.resolve(data.sics);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                } else {
                    deferred.resolve(sics);
                }

                return deferred.promise;
            }

            function getEntities(){
                var deferred = $q.defer();

                if(entities === undefined){
                    init()
                        .then(
                            function (data) {
                                setEntities(data.entities);
                                deferred.resolve(data.entities);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(entities);
                }

                return deferred.promise;
            }

            function getYears(){
                var deferred = $q.defer();

                if(years === undefined){
                    init()
                        .then(
                            function (data) {
                                setYears(data.years);
                                deferred.resolve(data.years);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(years);
                }

                return deferred.promise;
            }

            function getPeriods(){
                var deferred = $q.defer();

                if(periods === undefined){
                    init()
                        .then(
                            function (data) {
                                setPeriods(data.periods);
                                deferred.resolve(data.periods);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(periods);
                }

                return deferred.promise;
            }

            function getTags(){
                var deferred = $q.defer();

                if(tags === undefined){
                    init()
                        .then(
                            function (data) {
                                setTags(data.tags);
                                deferred.resolve(data.tags);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(tags);
                }

                return deferred.promise;
            }

            function setSics(lSics){
                if(lSics !== undefined && lSics !== null && typeof lSics === 'object' && lSics.length !== undefined) {
                    sics = lSics;
                }
            }

            function setEntities(lEntities){
                if(lEntities !== undefined && lEntities !== null && typeof lEntities === 'object' && lEntities.length !== undefined) {
                    entities = lEntities;
                }
            }

            function setYears(lYears){
                if(lYears !== undefined && lYears !== null && typeof lYears === 'object' && lYears.length !== undefined) {
                    years = lYears;
                }
            }

            function setPeriods(lPeriods){
                if(lPeriods !== undefined && lPeriods !== null && typeof lPeriods === 'object' && lPeriods.length !== undefined) {
                    periods = lPeriods;
                }
            }

            function setTags(lTags){
                if(lTags !== undefined && lTags !== null && typeof lTags === 'object' && lTags.length !== undefined) {
                    tags = lTags;
                }
            }

            function arrayContains(array, value){
                if(array === undefined || array === null || array.length === 0){
                    return false;
                }
                for( var i=0; i < array.length; i++){
                    if (array[i] === value) {
                        return true;
                    }
                }
                return false;
            }

            function selectEntity(entity) {
                if (selection.cik)
                {
                    if (!arrayContains(selection.cik, entity.cik)) {
                        selection.cik.push(entity.cik);
                    }
                }
                else
                {
                    selection.cik = [ entity.cik ];
                }
            }

            function selectSic(sic) {
                if (selection.sic)
                {
                    if (!arrayContains(selection.sic, sic.ID)) {
                        selection.sic.push(sic.ID);
                    }
                }
                else
                {
                    selection.sic = [ sic.ID ];
                }
            }

            function getEntity(cik){
                var result;
                if(entities !== undefined) {
                    entities.forEach(function (entity) {
                        if (entity.cik === cik) {
                            result = entity;
                        }
                    });
                }
                return result;
            }

            function getSic(sicCode){
                var result;
                if(sics !== undefined) {
                    sics.forEach(function (sic) {
                        if (sic.ID === sicCode) {
                            result = sic;
                        }
                    });
                }
                return result;
            }

            function isLatestFiscalYearSelected(){
                var hasLatest = false;
                if((selection.fiscalYear.length || 0) > 0){
                    selection.fiscalYear.forEach(
                        function(year){
                            if(year === 'LATEST'){
                                hasLatest = true;
                            }
                        });
                }
                return hasLatest;
            }

            function getAspects(){
                var deferred = $q.defer();

                var hasLatest = isLatestFiscalYearSelected();
                var aspects = {
                    'sec:FiscalPeriod': selection.fiscalPeriod,
                    'sec:FiscalYear': [],
                    'xbrl:Entity': [],
                    'sec:Archive':[]
                };

                // fiscal year
                if((selection.fiscalYear.length || 0) > 0){
                    if(!hasLatest) {
                        selection.fiscalYear.forEach(
                            function (year) {
                                aspects['sec:FiscalYear'].push(parseInt(year, 10));
                            }
                        );
                    } else {
                        selection.fiscalYear = ['LATEST'];
                    }
                }

                // cik
                if((selection.cik.length || 0) > 0){
                    selection.cik.forEach(function(cik){
                        if(!arrayContains(aspects['xbrl:Entity'], cik)){
                            aspects['xbrl:Entity'].push(cik);
                        }
                    });
                }

                // tag
                if((selection.tag.length || 0)  > 0){
                    selection.tag.forEach(function(tag){
                        entities.forEach(function(entity){
                            if(arrayContains(entity.tags, tag)){
                                if(!arrayContains(aspects['xbrl:Entity'], entity.cik)){
                                    aspects['xbrl:Entity'].push(entity.cik);
                                }
                            }
                        });
                    });
                }

                // sic
                if((selection.sic.length || 0)  > 0){
                    selection.sic.forEach(function(sic){
                        entities.forEach(function(entity){
                            if(entity.sic === '' + sic){
                                if(!arrayContains(aspects['xbrl:Entity'], entity.cik)){
                                    aspects['xbrl:Entity'].push(entity.cik);
                                }
                            }
                        });
                    });
                }

                if(hasLatest) {
                    // restrict sec:Archives in case Fiscal Year is latest
                    var parameters = {
                        $method: 'POST',
                        cik: aspects['xbrl:Entity'],
                        fiscalYear: [ 'LATEST' ],
                        fiscalPeriod: aspects['sec:FiscalPeriod'],
                        token: Session.getToken()
                    };
                    API.Queries.listFilings(parameters)
                        .then(
                        function (filings) {
                            var archives = filings.Archives;
                            if ((archives.length || 0) > 0) {
                                if (aspects['sec:Archive'] === undefined) {
                                    aspects['sec:Archive'] = [];
                                }
                                archives.forEach(function (archive) {
                                    var aid = archive.AccessionNumber;
                                    if (!arrayContains(aspects['sec:Archive'], aid)) {
                                        aspects['sec:Archive'].push(aid);
                                    }
                                });
                            }
                            deferred.resolve(aspects);
                        }
                    );
                } else {
                    deferred.resolve(aspects);
                }

                return deferred.promise;
            }

            function resetSelection(report){
                var deferred = $q.defer();

                selection = report.resetFilters();

                var date = new Date();
                var year = date.getFullYear();
                var month = date.getMonth();
                if(month < 8){
                    year = year - 1;
                }
                var yearsPromise = getYears()
                    .then(function(years){
                        if(arrayContains(years, year)){
                            selection.fiscalYear = [year];
                        } else {
                            selection.fiscalYear = [years[1]];
                        }
                    });
                var periodsPromise = getPeriods()
                    .then(function(periods){selection.fiscalPeriod = [periods[0]];});
                $q.all([yearsPromise, periodsPromise])
                    .then(function(){
                        getAspects()
                            .then(
                                function (aspects) {
                                    if (report !== undefined && typeof report === 'object') {
                                        report.updateAspects(aspects);
                                    }
                                }
                            );
                        deferred.resolve(selection);
                    });

                return deferred.promise;
            }

            function getSelection(report){
                var deferred = $q.defer();

                selection = report.getFilters();

                if(selection === undefined){
                    resetSelection(report)
                        .then(
                            function(selection){
                                deferred.resolve(selection);
                            }
                        );
                } else {
                    deferred.resolve(selection);
                }
                return deferred.promise;
            }

            return {
                getSics: getSics,
                getSic: getSic,
                selectSic: selectSic,
                getEntities: getEntities,
                getEntity: getEntity,
                selectEntity: selectEntity,
                getYears: getYears,
                isLatestFiscalYearSelected: isLatestFiscalYearSelected,
                getPeriods: getPeriods,
                getTags: getTags,
                getSelection: getSelection,
                resetSelection: resetSelection,
                getAspects: getAspects
            };
        })();
    });
<commit_msg>Remove unused variables<commit_after>'use strict';

angular
    .module('filter-model', ['constants', 'api'])
    .factory('Filter', function($q, API, Session){

        return (function() {

            var promise;
            var selection;
            var sics, years, periods, entities, tags;

            function init(){
                if(promise === undefined) {
                    var deferred = $q.defer();

                    API.Report.getParameters({$method: 'POST'})
                        .then(
                            function (data) {
                                setSics(data.sics);
                                setEntities(data.entities);
                                setYears(data.years);
                                setPeriods(data.periods);
                                setTags(data.tags);
                                promise = undefined;
                                deferred.resolve(data);
                            },
                            function (e) {
                                promise = undefined;
                                deferred.reject(e);
                            }
                        );

                    promise = deferred.promise;
                }
                return promise;
            }

            function getSics(){
                var deferred = $q.defer();

                if(sics === undefined){
                    init()
                        .then(
                            function (data) {
                                setSics(data.sics);
                                deferred.resolve(data.sics);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                } else {
                    deferred.resolve(sics);
                }

                return deferred.promise;
            }

            function getEntities(){
                var deferred = $q.defer();

                if(entities === undefined){
                    init()
                        .then(
                            function (data) {
                                setEntities(data.entities);
                                deferred.resolve(data.entities);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(entities);
                }

                return deferred.promise;
            }

            function getYears(){
                var deferred = $q.defer();

                if(years === undefined){
                    init()
                        .then(
                            function (data) {
                                setYears(data.years);
                                deferred.resolve(data.years);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(years);
                }

                return deferred.promise;
            }

            function getPeriods(){
                var deferred = $q.defer();

                if(periods === undefined){
                    init()
                        .then(
                            function (data) {
                                setPeriods(data.periods);
                                deferred.resolve(data.periods);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(periods);
                }

                return deferred.promise;
            }

            function getTags(){
                var deferred = $q.defer();

                if(tags === undefined){
                    init()
                        .then(
                            function (data) {
                                setTags(data.tags);
                                deferred.resolve(data.tags);
                            },
                            function (e) {
                                deferred.reject(e);
                            }
                        );
                }else {
                    deferred.resolve(tags);
                }

                return deferred.promise;
            }

            function setSics(lSics){
                if(lSics !== undefined && lSics !== null && typeof lSics === 'object' && lSics.length !== undefined) {
                    sics = lSics;
                }
            }

            function setEntities(lEntities){
                if(lEntities !== undefined && lEntities !== null && typeof lEntities === 'object' && lEntities.length !== undefined) {
                    entities = lEntities;
                }
            }

            function setYears(lYears){
                if(lYears !== undefined && lYears !== null && typeof lYears === 'object' && lYears.length !== undefined) {
                    years = lYears;
                }
            }

            function setPeriods(lPeriods){
                if(lPeriods !== undefined && lPeriods !== null && typeof lPeriods === 'object' && lPeriods.length !== undefined) {
                    periods = lPeriods;
                }
            }

            function setTags(lTags){
                if(lTags !== undefined && lTags !== null && typeof lTags === 'object' && lTags.length !== undefined) {
                    tags = lTags;
                }
            }

            function arrayContains(array, value){
                if(array === undefined || array === null || array.length === 0){
                    return false;
                }
                for( var i=0; i < array.length; i++){
                    if (array[i] === value) {
                        return true;
                    }
                }
                return false;
            }

            function selectEntity(entity) {
                if (selection.cik)
                {
                    if (!arrayContains(selection.cik, entity.cik)) {
                        selection.cik.push(entity.cik);
                    }
                }
                else
                {
                    selection.cik = [ entity.cik ];
                }
            }

            function selectSic(sic) {
                if (selection.sic)
                {
                    if (!arrayContains(selection.sic, sic.ID)) {
                        selection.sic.push(sic.ID);
                    }
                }
                else
                {
                    selection.sic = [ sic.ID ];
                }
            }

            function getEntity(cik){
                var result;
                if(entities !== undefined) {
                    entities.forEach(function (entity) {
                        if (entity.cik === cik) {
                            result = entity;
                        }
                    });
                }
                return result;
            }

            function getSic(sicCode){
                var result;
                if(sics !== undefined) {
                    sics.forEach(function (sic) {
                        if (sic.ID === sicCode) {
                            result = sic;
                        }
                    });
                }
                return result;
            }

            function isLatestFiscalYearSelected(){
                var hasLatest = false;
                if((selection.fiscalYear.length || 0) > 0){
                    selection.fiscalYear.forEach(
                        function(year){
                            if(year === 'LATEST'){
                                hasLatest = true;
                            }
                        });
                }
                return hasLatest;
            }

            function getAspects(){
                var deferred = $q.defer();

                var hasLatest = isLatestFiscalYearSelected();
                var aspects = {
                    'sec:FiscalPeriod': selection.fiscalPeriod,
                    'sec:FiscalYear': [],
                    'xbrl:Entity': [],
                    'sec:Archive':[]
                };

                // fiscal year
                if((selection.fiscalYear.length || 0) > 0){
                    if(!hasLatest) {
                        selection.fiscalYear.forEach(
                            function (year) {
                                aspects['sec:FiscalYear'].push(parseInt(year, 10));
                            }
                        );
                    } else {
                        selection.fiscalYear = ['LATEST'];
                    }
                }

                // cik
                if((selection.cik.length || 0) > 0){
                    selection.cik.forEach(function(cik){
                        if(!arrayContains(aspects['xbrl:Entity'], cik)){
                            aspects['xbrl:Entity'].push(cik);
                        }
                    });
                }

                // tag
                if((selection.tag.length || 0)  > 0){
                    selection.tag.forEach(function(tag){
                        entities.forEach(function(entity){
                            if(arrayContains(entity.tags, tag)){
                                if(!arrayContains(aspects['xbrl:Entity'], entity.cik)){
                                    aspects['xbrl:Entity'].push(entity.cik);
                                }
                            }
                        });
                    });
                }

                // sic
                if((selection.sic.length || 0)  > 0){
                    selection.sic.forEach(function(sic){
                        entities.forEach(function(entity){
                            if(entity.sic === '' + sic){
                                if(!arrayContains(aspects['xbrl:Entity'], entity.cik)){
                                    aspects['xbrl:Entity'].push(entity.cik);
                                }
                            }
                        });
                    });
                }

                if(hasLatest) {
                    // restrict sec:Archives in case Fiscal Year is latest
                    var parameters = {
                        $method: 'POST',
                        cik: aspects['xbrl:Entity'],
                        fiscalYear: [ 'LATEST' ],
                        fiscalPeriod: aspects['sec:FiscalPeriod'],
                        token: Session.getToken()
                    };
                    API.Queries.listFilings(parameters)
                        .then(
                        function (filings) {
                            var archives = filings.Archives;
                            if ((archives.length || 0) > 0) {
                                if (aspects['sec:Archive'] === undefined) {
                                    aspects['sec:Archive'] = [];
                                }
                                archives.forEach(function (archive) {
                                    var aid = archive.AccessionNumber;
                                    if (!arrayContains(aspects['sec:Archive'], aid)) {
                                        aspects['sec:Archive'].push(aid);
                                    }
                                });
                            }
                            deferred.resolve(aspects);
                        }
                    );
                } else {
                    deferred.resolve(aspects);
                }

                return deferred.promise;
            }

            function resetSelection(report){
                var deferred = $q.defer();

                selection = report.resetFilters();

                var date = new Date();
                var year = date.getFullYear();
                var month = date.getMonth();
                if(month < 8){
                    year = year - 1;
                }
                var yearsPromise = getYears()
                    .then(function(years){
                        if(arrayContains(years, year)){
                            selection.fiscalYear = [year];
                        } else {
                            selection.fiscalYear = [years[1]];
                        }
                    });
                var periodsPromise = getPeriods()
                    .then(function(periods){selection.fiscalPeriod = [periods[0]];});
                $q.all([yearsPromise, periodsPromise])
                    .then(function(){
                        getAspects()
                            .then(
                                function (aspects) {
                                    if (report !== undefined && typeof report === 'object') {
                                        report.updateAspects(aspects);
                                    }
                                }
                            );
                        deferred.resolve(selection);
                    });

                return deferred.promise;
            }

            function getSelection(report){
                var deferred = $q.defer();

                selection = report.getFilters();

                if(selection === undefined){
                    resetSelection(report)
                        .then(
                            function(selection){
                                deferred.resolve(selection);
                            }
                        );
                } else {
                    deferred.resolve(selection);
                }
                return deferred.promise;
            }

            return {
                getSics: getSics,
                getSic: getSic,
                selectSic: selectSic,
                getEntities: getEntities,
                getEntity: getEntity,
                selectEntity: selectEntity,
                getYears: getYears,
                isLatestFiscalYearSelected: isLatestFiscalYearSelected,
                getPeriods: getPeriods,
                getTags: getTags,
                getSelection: getSelection,
                resetSelection: resetSelection,
                getAspects: getAspects
            };
        })();
    });
<|endoftext|>


<commit_before>import { combineReducers }  from 'redux';

import backgrounds from './Backgrounds';
import board from './Board';
import icons from './Icons';

export default combineReducers({
    backgrounds,
    board,
    icons,
});<commit_msg>updare reducer<commit_after>import { combineReducers }  from 'redux';

import backgrounds from './Backgrounds';
import board from './Board';
import icons from './Icons';

export default combineReducers({
    backgrounds,
    board,
    icons,
});
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp')

.service('Answers', ['$firebaseArray', '$rootScope', '$http', function($firebaseArray, $rootScope, $http) {
  var ref = firebase.database().ref().child("answers");
  var answersStatsRef = firebase.database().ref().child("answers-aggregated");
  var firebaseStats;
  var answerStatsHashed = {};

  var api = {};

  api.answers = [];//$firebaseArray(ref);
  api.ipAddress;

  var json = 'https://ipv4.myexternalip.com/json';
  $http.get(json).then(function(result) {
      api.ipAddress = result.data.ip;
      var query = ref.orderByChild("ipAddress").equalTo(api.ipAddress);
      api.answers = $firebaseArray(query);
      $rootScope.$emit("answers-loaded", api.answers);
  }, function(e) {
      alert("error");
  });

  function loadStats () {
    firebaseStats = $firebaseArray(answersStatsRef);
    firebaseStats.$loaded(function (firebaseStats) {
      for (var index in firebaseStats) {
        var stat = firebaseStats[index];
        answerStatsHashed[stat.questionId] = stat;
      }
    });
  }
  loadStats();

  function updateStats(questionId, choice, oldChoice) {
    var stat = answerStatsHashed[questionId];
    if (!stat) {
      var statObject = {
        questionId: questionId,
      };
      statObject[choice] = 1;
      firebaseStats.$add(statObject);
    } else {
      if (!stat[choice]) stat[choice] = 0;
      if (oldChoice !== choice) stat[choice] += 1;
      if (stat[oldChoice] && oldChoice !== choice) stat[oldChoice] -= 1;
      firebaseStats.$save(stat);
    }
  };

  api.loadAnswers = function (facebookUserId) {
    var query = ref.orderByChild("facebookUserId").equalTo(facebookUserId);
    api.answers = $firebaseArray(query);
    $rootScope.$emit("answers-loaded", api.answers);
    return api.answers;
  };

  api.answerQuestion = function (questionId, choice, facebookUserId) {
    let answer = this.getAnswerForQuestion(questionId);
    let oldChoice;
    if (answer) {
      oldChoice = angular.copy(answer.choice);
      answer.choice = choice;
      answer.facebookUserId = facebookUserId;
      answer.ipAddress = api.ipAddress;
      api.answers.$save(answer);
    } else {
      api.answers.$add({
        questionId: questionId,
        choice: choice,
        facebookUserId: facebookUserId,
        ipAddress: api.ipAddress,
      });
    }
    updateStats(questionId, choice, oldChoice);
  };

  api.getAnswerForQuestion = function (questionId) {
    for (var index in api.answers) {
      var answer = api.answers[index];
      if (answer.questionId === questionId) return answer;
    }
    return null;
  };

  api.getAnswerStatsForQuestion = function (questionId) {
    for (var index in firebaseStats) {
      var answer = firebaseStats[index];
      if (answer.questionId === questionId) return answer;
    }
    return null;
  };

  return api;
}]);
<commit_msg>Fixed some linking<commit_after>'use strict';

angular.module('myApp')

.service('Answers', ['$firebaseArray', '$rootScope', '$http', function($firebaseArray, $rootScope, $http) {
  var ref = firebase.database().ref().child("answers");
  var answersStatsRef = firebase.database().ref().child("answers-aggregated");
  var firebaseStats;
  var answerStatsHashed = {};

  var api = {};

  api.answers = [];//$firebaseArray(ref);
  api.ipAddress;

  var json = 'https://ipv4.myexternalip.com/json';
  $http.get(json).then(function(result) {
      api.ipAddress = result.data.ip;
      var query = ref.orderByChild("ipAddress").equalTo(api.ipAddress);
      api.answers = $firebaseArray(query);
      $rootScope.$emit("answers-loaded", api.answers);
  }, function(e) {
      alert("error");
  });

  function loadStats () {
    firebaseStats = $firebaseArray(answersStatsRef);
    firebaseStats.$loaded(function (firebaseStats) {
      for (var index in firebaseStats) {
        var stat = firebaseStats[index];
        answerStatsHashed[stat.questionId] = stat;
      }
    });
  }
  loadStats();

  function updateStats(questionId, choice, oldChoice) {
    var stat = answerStatsHashed[questionId];
    if (!stat) {
      var statObject = {
        questionId: questionId,
      };
      statObject[choice] = 1;
      firebaseStats.$add(statObject);
      loadStats();
    } else {
      if (!stat[choice]) stat[choice] = 0;
      if (oldChoice !== choice) stat[choice] += 1;
      if (stat[oldChoice] && oldChoice !== choice) stat[oldChoice] -= 1;
      firebaseStats.$save(stat);
    }
  };

  api.loadAnswers = function (facebookUserId) {
    for (var index in api.answers) {
      let answer = api.answers[index];
      answer.facebookUserId = facebookUserId;
      api.answers.$save(answer);
    }
    var query = ref.orderByChild("facebookUserId").equalTo(facebookUserId);
    api.answers = $firebaseArray(query);
    $rootScope.$emit("answers-loaded", api.answers);
    return api.answers;
  };

  api.answerQuestion = function (questionId, choice, facebookUserId) {
    let answer = this.getAnswerForQuestion(questionId);
    let oldChoice;
    if (answer) {
      oldChoice = angular.copy(answer.choice);
      answer.choice = choice;
      if (facebookUserId) answer.facebookUserId = facebookUserId;
      answer.ipAddress = api.ipAddress;
      api.answers.$save(answer);
    } else {
      let answer = {
        questionId: questionId,
        choice: choice,
        // facebookUserId: facebookUserId,
        ipAddress: api.ipAddress,
      };
      if (facebookUserId) answer.facebookUserId = facebookUserId;
      api.answers.$add(answer);
    }
    updateStats(questionId, choice, oldChoice);
  };

  api.getAnswerForQuestion = function (questionId) {
    for (var index in api.answers) {
      var answer = api.answers[index];
      if (answer.questionId === questionId) return answer;
    }
    return null;
  };

  api.getAnswerStatsForQuestion = function (questionId) {
    for (var index in firebaseStats) {
      var answer = firebaseStats[index];
      if (answer.questionId === questionId) return answer;
    }
    return null;
  };

  return api;
}]);
<|endoftext|>