<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
**/

// Setup a text input that the user will use to input a path to a local file.
App.Directives.directive('predictiveFileBrowserInput', function() {
	var link = function($scope, $elem, $attrs) {
		$scope.autocomplete = [];

		// Set id to use this directive correctly in multiple places
		$scope.id = 'autoCompletePath'+ $elem.context.id
		/*
		 * We need a place to dump our auto-completion options
		 */
		$($elem).parent().append('

');

		// Handle user clicks on auto-complete path options
		$(document).on('click', '#' +$scope.id+ ' li span', function(e) {
			// Set the input text box's value to that of the user selected path
			var val = $(e.target).text();
			$($elem).val(val);
			// Need to trigger the input box's "input" event so Angular updates the model!
			$elem.trigger('input');

			// If the user selected a directory, find more results..
			if (val[val.length - 1] == '/') {
				$scope.fetchFiles($($elem).val());
			// Otherwise, remove the auto-complete options...
			} else {
				$('#' +$scope.id+ ' li').remove();
			}
		});

		/*
		 * Handle key-down events on the input box
		 *
		 * We need to ignore <TAB> presses here so we can auto-complete with <TAB>.
		 * If we don't ignore here then <TAB> will move the user to the next field
		 * in the form and our common-prefix-fill won't work later.
		 */
		$($elem).keydown(function(e) {
			var code = e.keyCode || e.which;
			var BACKSPACE = 8,
				TAB = 9;

			if (code == TAB)
				return false;
		});

		/*
		 * Handle key-up events on the input box
		 */
		$($elem).keyup(function(e) {
			var code = e.keyCode || e.which;
			var BACKSPACE = 8,
				TAB = 9,
				FORWARD_SLASH = 191;

			if (code === FORWARD_SLASH) {
				// Fetch new directory information from the server.
				$scope.fetchFiles($(this).val());
			} else if (code === TAB) {
				// Attempt to auto-fill for the user.
				$scope.handleTabPress();
			} else if (code == BACKSPACE) {
				// Need to properly handle the removal of directory information
				// and the displaying of auto-complete options
				$scope.handleBackSpace();
			} else {
				// Filter auto-complete options based on user input..
				$scope.handleMiscKeyPress();
			}

			// This is being used so we can handle backspacing. The user might hold
			// down the backspace key or select a section of text and delete. This allows
			// us to compare the result to its prior state, which makes handling
			// backspaces easier.
			$scope.lastInputContents = $elem.val();
		});

		/*
		 * Grab additional path information from the web-server
		 *
		 * Params:
		 *		path - The path to get a directory listing of.
		 */
		// TODO Make this use $HTTP
		$scope.fetchFiles = function(path) {
			$.get($scope.baseURL + '/getDirInfo/' + path, {},
				 function(data) {
					 $scope.setNewData(data);
					 $scope.updateAutoComplete();
				 }, 'json');
		};

		/*
		 * Grab additional path information from the web-server and filter the
		 * results based on the current input text.
		 *
		 * Params:
		 *		path - The path to get a directory listing of.
		 *
		 * This is needed to handle deletion of selected text. It is possible that
		 * the user will select text and delete only part of a word. The results
		 * need to be filtered based on this partial input.
		 */
		// TODO Why isn't this using $http?!?!?! Because I copy and pasted!!!!
		$scope.fetchFilesAndFilter = function(path) {
			$.get($scope.baseURL + '/getDirInfo/' + path, {},
				 function(data) {
					 $scope.setNewData(data);
					 $scope.filterResults();
					 $scope.updateAutoComplete();
				 }, 'json');
		};

		/*
		 * Handle directory data from the server.
		 *
		 * We store the entire directory information along with the remaining
		 * possible options given the users current input. This lets us avoid
		 * unnecessary calls to the server for directory information every time
		 * the user deletes something.
		 */
		$scope.setNewData = function(data) {
			$scope.autocomplete = data.sort();
			$scope.possibleCompletes = $scope.autocomplete;
		};

		/*
		 * Handle <TAB> presses.
		 *
		 * Attempt to auto-complete options when the user presses <TAB>.
		 */
		$scope.handleTabPress = function() {
			// If there's only one option available there's no points in trying to
			// find a common prefix! Just set the value!
			if ($scope.possibleCompletes.length === 1) {
				$elem.val($scope.possibleCompletes[0]);

				// Make sure more options are displayed if a directory was selected.
				$scope.checkForMoreOptions();
				$scope.updateAutoComplete();
				return;
			}

			// Find the greatest common prefix amongst the remaining choices and set
			// the input text to it.
			var prefix = $scope.getLargestCommonPrefix($scope.possibleCompletes);
			$elem.val(prefix);
			$scope.updateAutoComplete();
		};

		/*
		 * Handle Backspacing and option displaying.
		 *
		 * The auto-complete options needs to be displayed correctly when the user
		 * removes directory information.
		 */
		$scope.handleBackSpace = function() {
			var curInputVal = $elem.val();

			// If the user deletes everything in the input box all we need to do
			// is make sure that the auto-complete options aren't displayed.
			if (curInputVal.length === 0) {
				$('#' +$scope.id+ ' li').remove();
				return;
			}

			// Figure out how much text the user removed from the input box.
			var lengthDiff = $scope.lastInputContents.length - curInputVal.length;
			// Grab the removed text.
			var removedText = $scope.lastInputContents.substr(-lengthDiff);

			// If the user deleted over a directory we need to fetch information on the
			// previous directory for auto-completion.
			if (removedText.indexOf('/') !== -1) {
				var lastSlashIndex = curInputVal.lastIndexOf('/');

				// If the remaining path still contains a directory...
				if (lastSlashIndex !== -1) {
					// Grab the section of the path that points to a valid directory,
					// fetch the listing, and update the results.
					var pathToSearch = curInputVal.slice(0, lastSlashIndex + 1);
					$scope.fetchFilesAndFilter(pathToSearch);
				} else {
					// Delete the old auto-complete information in the case where the user
					// completely removed path information.
					$('#' +$scope.id+ ' li').remove();
				}
			} else {
				// Otherwise, we just need to filter results based on the remaining input.
				$scope.filterResults();
				$scope.updateAutoComplete();
			}
		};

		/*
		 * Handle all other key presses in the input box
		 *
		 * Filter the auto-complete options as the user types to ensure that only options
		 * which are possible given the current input text are still displayed.
		 */
		$scope.handleMiscKeyPress = function() {
			// Safely exit when there are no options available.
			if ($scope.autocomplete === [])
				return;

			// Otherwise, filter the results.
			$scope.filterResults();
			$scope.updateAutoComplete();
		};

		/*
		 * When a path is auto-completed with <TAB> we need to check to see if it points
		 * to a directory. If it does, we still need to fetch results!
		 */
		$scope.checkForMoreOptions = function() {
			var path = $elem.val();
			if (path[path.length - 1] === '/') {
				$scope.fetchFiles(path);
			}
		};

		/*
		 * Calculate the greatest common prefix of the passed options.
		 *
		 * Params:
		 *		Options - An array of strings in which the greatest common prefix
		 *				  should be found
		 *
		 * Returns:
		 *		The greatest common prefix of the strings.
		 *
		 *
		 * Note - For us, there will always be a prefix of at least '/' since this can't
		 * possible be called without the users entering a starting directory. As a result,
		 * we don't explicitly handle the case where there is 0 length common prefix.
		 */
		$scope.getLargestCommonPrefix = function(options) {
			var index = 1;
			var shortestString = options.reduce(function(a, b) { return a.length  b.length ? a : b; });
			var	substringToCheck = shortestString[0];

			while (longestString.indexOf(substringToCheck) !== -1) {
				substringToCheck = shortestString.slice(0, ++index);
			}

			return longestString.slice(0, index - 1);
		};

		/*
		 * Filter the auto-complete options based on the current input.
		 */
		$scope.filterResults = function() {
			$scope.possibleCompletes = $scope.autocomplete.filter(function(item, index, array) {
				return (~item.indexOf($($elem).val()));
			});

			$scope.possibleCompletes.sort();
		};

		/*
		 * Update the display of auto-complete options.
		 */
		$scope.updateAutoComplete = function() {
			// Remove all the existing options
			$('#' +$scope.id+ ' li').remove();

			// We don't need to show anything if the user has completely selected
			// the only existing option available.
			if ($scope.possibleCompletes.length === 1) {
				if ($scope.possibleCompletes[0] === $elem.val()) {
					return;
				}
			}

			// Display all the possible completes
			$.each($scope.possibleCompletes, function(i, v) {
				$('#' +$scope.id+ '').append($('
').html($('').text(v)));
			});
		};
	};

	return {
		link: link,
		scope: true,
		restrict: 'A'
	};
});
<commit_msg>CLIMATE-333 - Update PredictiveFileBrowserInput endpoints<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
**/

// Setup a text input that the user will use to input a path to a local file.
App.Directives.directive('predictiveFileBrowserInput', function() {
	var link = function($scope, $elem, $attrs) {
		$scope.autocomplete = [];

		// Set id to use this directive correctly in multiple places
		$scope.id = 'autoCompletePath'+ $elem.context.id
		/*
		 * We need a place to dump our auto-completion options
		 */
		$($elem).parent().append('

');

		// Handle user clicks on auto-complete path options
		$(document).on('click', '#' +$scope.id+ ' li span', function(e) {
			// Set the input text box's value to that of the user selected path
			var val = $(e.target).text();
			$($elem).val(val);
			// Need to trigger the input box's "input" event so Angular updates the model!
			$elem.trigger('input');

			// If the user selected a directory, find more results..
			if (val[val.length - 1] == '/') {
				$scope.fetchFiles($($elem).val());
			// Otherwise, remove the auto-complete options...
			} else {
				$('#' +$scope.id+ ' li').remove();
			}
		});

		/*
		 * Handle key-down events on the input box
		 *
		 * We need to ignore <TAB> presses here so we can auto-complete with <TAB>.
		 * If we don't ignore here then <TAB> will move the user to the next field
		 * in the form and our common-prefix-fill won't work later.
		 */
		$($elem).keydown(function(e) {
			var code = e.keyCode || e.which;
			var BACKSPACE = 8,
				TAB = 9;

			if (code == TAB)
				return false;
		});

		/*
		 * Handle key-up events on the input box
		 */
		$($elem).keyup(function(e) {
			var code = e.keyCode || e.which;
			var BACKSPACE = 8,
				TAB = 9,
				FORWARD_SLASH = 191;

			if (code === FORWARD_SLASH) {
				// Fetch new directory information from the server.
				$scope.fetchFiles($(this).val());
			} else if (code === TAB) {
				// Attempt to auto-fill for the user.
				$scope.handleTabPress();
			} else if (code == BACKSPACE) {
				// Need to properly handle the removal of directory information
				// and the displaying of auto-complete options
				$scope.handleBackSpace();
			} else {
				// Filter auto-complete options based on user input..
				$scope.handleMiscKeyPress();
			}

			// This is being used so we can handle backspacing. The user might hold
			// down the backspace key or select a section of text and delete. This allows
			// us to compare the result to its prior state, which makes handling
			// backspaces easier.
			$scope.lastInputContents = $elem.val();
		});

		/*
		 * Grab additional path information from the web-server
		 *
		 * Params:
		 *		path - The path to get a directory listing of.
		 */
		// TODO Make this use $HTTP
		$scope.fetchFiles = function(path) {
			$.get($scope.baseURL + '/dir/list/' + path, {},
				 function(data) {
					 data = data['listing']
					 $scope.setNewData(data);
					 $scope.updateAutoComplete();
				 }, 'json');
		};

		/*
		 * Grab additional path information from the web-server and filter the
		 * results based on the current input text.
		 *
		 * Params:
		 *		path - The path to get a directory listing of.
		 *
		 * This is needed to handle deletion of selected text. It is possible that
		 * the user will select text and delete only part of a word. The results
		 * need to be filtered based on this partial input.
		 */
		// TODO Why isn't this using $http?!?!?! Because I copy and pasted!!!!
		$scope.fetchFilesAndFilter = function(path) {
			$.get($scope.baseURL + '/dir/list/' + path, {},
				 function(data) {
					 data = data['listing']
					 $scope.setNewData(data);
					 $scope.filterResults();
					 $scope.updateAutoComplete();
				 }, 'json');
		};

		/*
		 * Handle directory data from the server.
		 *
		 * We store the entire directory information along with the remaining
		 * possible options given the users current input. This lets us avoid
		 * unnecessary calls to the server for directory information every time
		 * the user deletes something.
		 */
		$scope.setNewData = function(data) {
			$scope.autocomplete = data.sort();
			$scope.possibleCompletes = $scope.autocomplete;
		};

		/*
		 * Handle <TAB> presses.
		 *
		 * Attempt to auto-complete options when the user presses <TAB>.
		 */
		$scope.handleTabPress = function() {
			// If there's only one option available there's no points in trying to
			// find a common prefix! Just set the value!
			if ($scope.possibleCompletes.length === 1) {
				$elem.val($scope.possibleCompletes[0]);

				// Make sure more options are displayed if a directory was selected.
				$scope.checkForMoreOptions();
				$scope.updateAutoComplete();
				return;
			}

			// Find the greatest common prefix amongst the remaining choices and set
			// the input text to it.
			var prefix = $scope.getLargestCommonPrefix($scope.possibleCompletes);
			$elem.val(prefix);
			$scope.updateAutoComplete();
		};

		/*
		 * Handle Backspacing and option displaying.
		 *
		 * The auto-complete options needs to be displayed correctly when the user
		 * removes directory information.
		 */
		$scope.handleBackSpace = function() {
			var curInputVal = $elem.val();

			// If the user deletes everything in the input box all we need to do
			// is make sure that the auto-complete options aren't displayed.
			if (curInputVal.length === 0) {
				$('#' +$scope.id+ ' li').remove();
				return;
			}

			// Figure out how much text the user removed from the input box.
			var lengthDiff = $scope.lastInputContents.length - curInputVal.length;
			// Grab the removed text.
			var removedText = $scope.lastInputContents.substr(-lengthDiff);

			// If the user deleted over a directory we need to fetch information on the
			// previous directory for auto-completion.
			if (removedText.indexOf('/') !== -1) {
				var lastSlashIndex = curInputVal.lastIndexOf('/');

				// If the remaining path still contains a directory...
				if (lastSlashIndex !== -1) {
					// Grab the section of the path that points to a valid directory,
					// fetch the listing, and update the results.
					var pathToSearch = curInputVal.slice(0, lastSlashIndex + 1);
					$scope.fetchFilesAndFilter(pathToSearch);
				} else {
					// Delete the old auto-complete information in the case where the user
					// completely removed path information.
					$('#' +$scope.id+ ' li').remove();
				}
			} else {
				// Otherwise, we just need to filter results based on the remaining input.
				$scope.filterResults();
				$scope.updateAutoComplete();
			}
		};

		/*
		 * Handle all other key presses in the input box
		 *
		 * Filter the auto-complete options as the user types to ensure that only options
		 * which are possible given the current input text are still displayed.
		 */
		$scope.handleMiscKeyPress = function() {
			// Safely exit when there are no options available.
			if ($scope.autocomplete === [])
				return;

			// Otherwise, filter the results.
			$scope.filterResults();
			$scope.updateAutoComplete();
		};

		/*
		 * When a path is auto-completed with <TAB> we need to check to see if it points
		 * to a directory. If it does, we still need to fetch results!
		 */
		$scope.checkForMoreOptions = function() {
			var path = $elem.val();
			if (path[path.length - 1] === '/') {
				$scope.fetchFiles(path);
			}
		};

		/*
		 * Calculate the greatest common prefix of the passed options.
		 *
		 * Params:
		 *		Options - An array of strings in which the greatest common prefix
		 *				  should be found
		 *
		 * Returns:
		 *		The greatest common prefix of the strings.
		 *
		 *
		 * Note - For us, there will always be a prefix of at least '/' since this can't
		 * possible be called without the users entering a starting directory. As a result,
		 * we don't explicitly handle the case where there is 0 length common prefix.
		 */
		$scope.getLargestCommonPrefix = function(options) {
			var index = 1;
			var shortestString = options.reduce(function(a, b) { return a.length  b.length ? a : b; });
			var	substringToCheck = shortestString[0];

			while (longestString.indexOf(substringToCheck) !== -1) {
				substringToCheck = shortestString.slice(0, ++index);
			}

			return longestString.slice(0, index - 1);
		};

		/*
		 * Filter the auto-complete options based on the current input.
		 */
		$scope.filterResults = function() {
			$scope.possibleCompletes = $scope.autocomplete.filter(function(item, index, array) {
				return (~item.indexOf($($elem).val()));
			});

			$scope.possibleCompletes.sort();
		};

		/*
		 * Update the display of auto-complete options.
		 */
		$scope.updateAutoComplete = function() {
			// Remove all the existing options
			$('#' +$scope.id+ ' li').remove();

			// We don't need to show anything if the user has completely selected
			// the only existing option available.
			if ($scope.possibleCompletes.length === 1) {
				if ($scope.possibleCompletes[0] === $elem.val()) {
					return;
				}
			}

			// Display all the possible completes
			$.each($scope.possibleCompletes, function(i, v) {
				$('#' +$scope.id+ '').append($('
').html($('').text(v)));
			});
		};
	};

	return {
		link: link,
		scope: true,
		restrict: 'A'
	};
});
<|endoftext|>


<commit_before>var CU = require('../compilerUtils'),
	U = require('../../../utils'),
	CONST = require('../../../common/constants'),
	_ = require('../../../lib/alloy/underscore')._;

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var code = '';

	// make symbol a local variable if necessary
	if (state.local) {
		args.symbol = CU.generateUniqueId();
	}

	// Generate runtime code
	code += (state.local ? 'var ' : '') + args.symbol + " = {"
	code += "properties:" + CU.generateStyleParams(
		state.styles,
		args.classes,
		args.id,
		CU.getNodeFullname(node),
		_.defaults(state.extraStyle || {}, args.createArgs || {}),
		state
	) + '};';

	// Update the parsing state
	return {
		parent: {
			node: node,
			symbol: args.symbol
		},
		local: state.local || false,
		model: state.model || undefined,
		condition: state.condition || undefined,
		styles: state.styles,
		code: code
	}
};<commit_msg>can't wrap everything in "properties", need to leave out bindId objects<commit_after>var CU = require('../compilerUtils'),
	U = require('../../../utils'),
	CONST = require('../../../common/constants'),
	_ = require('../../../lib/alloy/underscore')._;

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var code = '';

	// make symbol a local variable if necessary
	if (state.local) {
		args.symbol = CU.generateUniqueId();
	}

	// Generate runtime code
	code += (state.local ? 'var ' : '') + args.symbol + " = "
	code += CU.generateStyleParams(
		state.styles,
		args.classes,
		args.id,
		CU.getNodeFullname(node),
		_.defaults(state.extraStyle || {}, args.createArgs || {}),
		_.extend(state, { isListItem: true })
	) + ';';

	// Update the parsing state
	return {
		parent: {
			node: node,
			symbol: args.symbol
		},
		local: state.local || false,
		model: state.model || undefined,
		condition: state.condition || undefined,
		styles: state.styles,
		code: code
	}
};<|endoftext|>


<commit_before>Meteor.methods(
    {
        getNotifications: function (user) {
            check(user, Object);
            check(user.userId, String);
            console.log('getNotifications entered' + JSON.stringify(user));
            //userId : user.userId
            var notificationsList = Notifications.find(
                {
                    $query: {
                        "userId": user.userId
                    }
                    ,
                    $orderby: {rowCreated: -1}
                }
            ).fetch();

            var pipeline1 = Notifications.find(
                {
                    $query: {
                        "userId": user.userId,
                        "status": 'Unread'
                    }
                }
            ).fetch();

            for (var i in notificationsList) {
                var notification = notificationsList[i];
                var id = notification.description.split("for")[1].replace(" ", "");
                var request = Aid.findOne({_id: id});
                console.log("aid" + notification.description.split("for")[0] + "for " + request.aidName);
                notification.description = notification.description.split("for")[0] + "for " + request.aidName;

                var notification = notificationsList[i];
                console.log(notification.requestId);
                var request = Request.findOne({_id: notification.requestId});
                console.log(request.request_name);
                notification.requestName = request.request_name;
            }
            console.log('notificationsList  ' + JSON.stringify(notificationsList));

            var count = []
            count.push({"count": pipeline1.length});

            console.log("count" + JSON.stringify(count));

            var combined = [];
            combined.push({"notification": notificationsList});
            combined.push({"count": count});
            console.log(JSON.stringify(combined));
            return combined;
        },

        getNotificationsHeader: function (user) {
            check(user, Object);
            check(user.userId, String);
            console.log('getNotifications entered' + JSON.stringify(user));
            //userId : user.userId
            var notificationsList = Notifications.find(
                {
                    $query: {
                        "userId": user.userId
                    }
                    ,
                    $orderby: {rowCreated: -1},
                    $limit: 5
                }
            ).fetch();

            var pipeline1 = Notifications.find(
                {
                    $query: {
                        "userId": user.userId,
                        "status": 'Unread'
                    }
                }
            ).fetch();

            for (var i in notificationsList) {
                var notification = notificationsList[i];
                var id = notification.description.split("for")[1].replace(" ", "");
                var request = Aid.findOne({_id: id});
                console.log("aid" + notification.description.split("for")[0] + "for " + request.aidName);
                notification.description = notification.description.split("for")[0] + "for " + request.aidName;

                var notification = notificationsList[i];
                console.log(notification.requestId);
                var request = Request.findOne({_id: notification.requestId});
                console.log(request.request_name);
                notification.requestName = request.request_name;
            }
            console.log('notificationsList  ' + JSON.stringify(notificationsList));

            var count = []
            count.push({"count": pipeline1.length});

            console.log("count" + JSON.stringify(count));

            var combined = [];
            combined.push({"notification": notificationsList});
            combined.push({"count": count});
            console.log(JSON.stringify(combined));
            return combined;
        }
    })
;

/*

 //update the status as read for retrieved notifications

 Notifications.update( {_id: { $in: notificationsArr }}, { $set :{"status": "Read"}}
 , function (error, result) {
 console.log("result " + result + ' error ' + error );
 if (error) {
 console.log("Errors !!" + error + "  Result - " + result);
 //TO-DO: error message()
 // throw new Meteor.Error("insert-failed", error.message);
 throw new Meteor.Error("update-failed", error);
 }
 });
 */

<commit_msg>Notification<commit_after>Meteor.methods(
    {
        getNotifications: function (user) {
            check(user, Object);
            check(user.userId, String);
            console.log('getNotifications entered' + JSON.stringify(user));
            //userId : user.userId
            var notificationsList = Notifications.find(
                {
                    $query: {
                        "userId": user.userId
                    }
                    ,
                    $orderby: {rowCreated: -1}
                }
            ).fetch();

            var pipeline1 = Notifications.find(
                {
                    $query: {
                        "userId": user.userId,
                        "status": 'Unread'
                    }
                }
            ).fetch();

            for (var i in notificationsList) {
                var notification = notificationsList[i];
                var id = notification.description.split("for")[1].replace(" ", "");
                var request = Aid.findOne({_id: id});
                console.log("aid" + notification.description.split("for")[0] + "for " + request.aidName);
                notification.description = notification.description.split("for")[0] + "for " + request.aidName;

                var notification = notificationsList[i];
                console.log(notification.requestId);
                var request = Request.findOne({_id: notification.requestId});
                console.log(request.request_name);
                notification.requestName = request.request_name;
            }
            console.log('notificationsList  ' + JSON.stringify(notificationsList));

            var count = []
            count.push({"count": pipeline1.length});

            console.log("count" + JSON.stringify(count));

            var combined = [];
            combined.push({"notification": notificationsList});
            combined.push({"count": count});
            console.log(JSON.stringify(combined));
            return combined;
        },

        getNotificationsHeader: function (user) {
            check(user, Object);
            check(user.userId, String);
            console.log('getNotifications entered' + JSON.stringify(user));
            //userId : user.userId
            var notificationsList = Notifications.find(
                {
                    $query: {
                        "userId": user.userId
                    }
                    ,
                    $orderby: {rowCreated: -1},
                    $limit: 5
                }
            ).fetch();

            var pipeline1 = Notifications.find(
                {
                    $query: {
                        "userId": user.userId,
                        "status": 'Unread'
                    }
                }
            ).fetch();

            for (var i in notificationsList) {
                /*var notification = notificationsList[i];
                var id = notification.description.split("for")[1].replace(" ", "");
                var request = Aid.findOne({_id: id});
                console.log("aid" + notification.description.split("for")[0] + "for " + request.aidName);
                notification.description = notification.description.split("for")[0] + "for " + request.aidName;*/

                var notification = notificationsList[i];
                console.log(notification.requestId);
                var request = Request.findOne({_id: notification.requestId});
                console.log(request.request_name);
                notification.requestName = request.request_name;
            }
            console.log('notificationsList  ' + JSON.stringify(notificationsList));

            var count = []
            count.push({"count": pipeline1.length});

            console.log("count" + JSON.stringify(count));

            var combined = [];
            combined.push({"notification": notificationsList});
            combined.push({"count": count});
            console.log(JSON.stringify(combined));
            return combined;
        }
    })
;

/*

 //update the status as read for retrieved notifications

 Notifications.update( {_id: { $in: notificationsArr }}, { $set :{"status": "Read"}}
 , function (error, result) {
 console.log("result " + result + ' error ' + error );
 if (error) {
 console.log("Errors !!" + error + "  Result - " + result);
 //TO-DO: error message()
 // throw new Meteor.Error("insert-failed", error.message);
 throw new Meteor.Error("update-failed", error);
 }
 });
 */

<|endoftext|>


<commit_before>define( 'argumenta/widgets/Proposition',
[
    "require-jquery",
    "argumenta/widgets/Base",
    "argumenta/widgets/AddTag",
    "argumenta/widgets/Tags",
    "text!./Proposition/template.html.mustache"
],
function( $, Base, AddTag, Tags, Template ) {

    var Proposition = Base.module( {

        moduleID: 'Proposition',
        template: Template,
        defaults: {
            index: 'P'
        },

        init: function( options ) {
            this.initProposition( options );
        },

        prototype: {

            getType: function() {
                return 'proposition';
            },

            getSha1: function() {
                return this.options.sha1;
            },

            initProposition: function( options ) {
                var self = this;

                // Show or hide proposition details on click
                self.element.on('click', function(event) {

                    // Don't trigger background elements on click
                    var closestWidget = $(event.target).closest('div[class*="widget"]');
                    if ( ! closestWidget.is(self.element) ) {
                        event.stopPropagation();
                        return true;
                    }

                    // Don't expand on mouse release after dragging
                    if (self.element.hasClass('ui-state-just-dragged'))
                        return;

                    // Don't interfere with links
                    if ($(event.target).is('a')) {
                        return true;
                    }

                    self._toggleDetails();
                });

                // Bind AddTag button
                self._bindAddTagButton();

                // Make draggable
                self._makeDraggable();
            },

            _toggleDetails: function() {

                var self = this;

                self._toggleTags();
            },

            _toggleTags: function() {

                var self = this;

                if ( typeof self.tags === "undefined" ) {
                    self._initTags();
                }
                else {
                    self.tags.element.toggle( 300 );
                }
            },

            _toggleAddTag: function() {

                var self = this;

                // Initialize if addTag necessary
                if ( typeof self.addTag === "undefined" ) {
                    self._initAddTag();
                    self.addTag.element.hide();
                }

                // Fade in or out
                self.addTag.element.toggle( 300 );
            },

            _initAddTag: function() {

                var self = this;

                // Create a new widget targeting this proposition
                var addTag = new AddTag( {
                    target_type: 'proposition',
                    target_sha1: self.getSha1()
                } );

                // Replace the placeholder
                self.element.children('.add-tag-widget')
                            .replaceWith( addTag.element );

                // Save a reference to the nested widget
                self.addTag = addTag;
            },

            _initTags: function() {
                var self = this;
                var tagsContainer = self.element.children('.proposition-details')
                                                .children('.tags-widget-container');

                // Hide the container
                tagsContainer.hide();

                // Create a new Tags widget targeting this proposition
                var tags = new Tags( {
                    target_type: self.getType(),
                    target_sha1: self.getSha1(),
                    onLoad: function( tagsWidget ) {
                        // Append the element and reveal the container
                        tagsContainer.append( tagsWidget.element );
                        tagsContainer.show( 300 );
                    }
                } );

                // Save a reference to the nested widget
                self.tags = tags;
            },

            _bindAddTagButton: function() {

                var self = this;

                $('.addtag-link', self.element).first().on( 'click', function(event) {

                    self._toggleAddTag();

                    // Defocus the link
                    $(this).blur();

                    // Prevent default & stop propagation
                    return false;
                } );
            },

            _makeDraggable: function() {

                var self = this;

                this.element.draggable( {
                    helper: 'clone',
                    appendTo: $('.drag-container')[0] || $('body'),
                    revert: true,
                    cancel: 'span, input',
                    handle: self.element.children(".proposition-main"),
                    cursor: 'move',
                    opacity: 0.90,
                    start: function(event, ui) {
                        // Prevent other actions on drag
                        ui.helper.addClass('ui-state-just-dragged proposition-widget-drag');

                        // Fix clone size
                        ui.helper.css( {
                            'height': self.element.height() + 'px',
                            'width': self.element.width() + 'px'
                        } );

                        // Hide original
                        self.element.css('visibility', "hidden");
                    },
                    stop: function(event, ui) {
                        // Prevent other actions on drag, then cleanup
                        setTimeout(function() {ui.helper.removeClass('ui-state-just-dragged');}, 300);

                        // Reveal original
                        self.element.css('visibility', "");
                    }
                } );
            },

            // Overrides Base
            _renderUI: function() {
                var self = this;

                self._super('_renderUI');

                var textElem = self.element.find('.text').first();
                var textHtml = textElem.html();
                var newHtml  = textHtml.replace(/\r?\n|\r/g, '
');

                textElem.html( newHtml );

                return;
            },

            // Overrides Base
            _getViewOptions: function() {
                var self = this;
                var role_desc;

                switch ( self.options.index ) {
                    case 'P': role_desc = '';              break;
                    case 'C': role_desc = ' (Conclusion)'; break;
                    default : role_desc = ' (Premise)';    break;
                }

                var viewOptions = {
                    partial_sha1: self.options.sha1.substr(0, 20),
                    proposition_desc: 'Proposition' + role_desc,
                    details_desc: 'Proposition details\r\nSHA1: ' + self.options.sha1
                }
                return $.extend( viewOptions, self.options );
            }
        }
    } );

    return Proposition;
} );
<commit_msg>fix dragged proposition size<commit_after>define( 'argumenta/widgets/Proposition',
[
    "require-jquery",
    "argumenta/widgets/Base",
    "argumenta/widgets/AddTag",
    "argumenta/widgets/Tags",
    "text!./Proposition/template.html.mustache"
],
function( $, Base, AddTag, Tags, Template ) {

    var Proposition = Base.module( {

        moduleID: 'Proposition',
        template: Template,
        defaults: {
            index: 'P'
        },

        init: function( options ) {
            this.initProposition( options );
        },

        prototype: {

            getType: function() {
                return 'proposition';
            },

            getSha1: function() {
                return this.options.sha1;
            },

            initProposition: function( options ) {
                var self = this;

                // Show or hide proposition details on click
                self.element.on('click', function(event) {

                    // Don't trigger background elements on click
                    var closestWidget = $(event.target).closest('div[class*="widget"]');
                    if ( ! closestWidget.is(self.element) ) {
                        event.stopPropagation();
                        return true;
                    }

                    // Don't expand on mouse release after dragging
                    if (self.element.hasClass('ui-state-just-dragged'))
                        return;

                    // Don't interfere with links
                    if ($(event.target).is('a')) {
                        return true;
                    }

                    self._toggleDetails();
                });

                // Bind AddTag button
                self._bindAddTagButton();

                // Make draggable
                self._makeDraggable();
            },

            _toggleDetails: function() {

                var self = this;

                self._toggleTags();
            },

            _toggleTags: function() {

                var self = this;

                if ( typeof self.tags === "undefined" ) {
                    self._initTags();
                }
                else {
                    self.tags.element.toggle( 300 );
                }
            },

            _toggleAddTag: function() {

                var self = this;

                // Initialize if addTag necessary
                if ( typeof self.addTag === "undefined" ) {
                    self._initAddTag();
                    self.addTag.element.hide();
                }

                // Fade in or out
                self.addTag.element.toggle( 300 );
            },

            _initAddTag: function() {

                var self = this;

                // Create a new widget targeting this proposition
                var addTag = new AddTag( {
                    target_type: 'proposition',
                    target_sha1: self.getSha1()
                } );

                // Replace the placeholder
                self.element.children('.add-tag-widget')
                            .replaceWith( addTag.element );

                // Save a reference to the nested widget
                self.addTag = addTag;
            },

            _initTags: function() {
                var self = this;
                var tagsContainer = self.element.children('.proposition-details')
                                                .children('.tags-widget-container');

                // Hide the container
                tagsContainer.hide();

                // Create a new Tags widget targeting this proposition
                var tags = new Tags( {
                    target_type: self.getType(),
                    target_sha1: self.getSha1(),
                    onLoad: function( tagsWidget ) {
                        // Append the element and reveal the container
                        tagsContainer.append( tagsWidget.element );
                        tagsContainer.show( 300 );
                    }
                } );

                // Save a reference to the nested widget
                self.tags = tags;
            },

            _bindAddTagButton: function() {

                var self = this;

                $('.addtag-link', self.element).first().on( 'click', function(event) {

                    self._toggleAddTag();

                    // Defocus the link
                    $(this).blur();

                    // Prevent default & stop propagation
                    return false;
                } );
            },

            _makeDraggable: function() {

                var self = this;

                this.element.draggable( {
                    helper: 'clone',
                    appendTo: $('.drag-container')[0] || $('body'),
                    revert: true,
                    cancel: 'span, input',
                    handle: self.element.children(".proposition-main"),
                    cursor: 'move',
                    opacity: 0.90,
                    start: function(event, ui) {
                        // Prevent other actions on drag
                        ui.helper.addClass('ui-state-just-dragged proposition-widget-drag');

                        // Fix clone size
                        ui.helper.css( {
                            'height': self.element.outerHeight() + 'px',
                            'width': self.element.outerWidth() + 'px'
                        } );

                        // Hide original
                        self.element.css('visibility', "hidden");
                    },
                    stop: function(event, ui) {
                        // Prevent other actions on drag, then cleanup
                        setTimeout(function() {ui.helper.removeClass('ui-state-just-dragged');}, 300);

                        // Reveal original
                        self.element.css('visibility', "");
                    }
                } );
            },

            // Overrides Base
            _renderUI: function() {
                var self = this;

                self._super('_renderUI');

                var textElem = self.element.find('.text').first();
                var textHtml = textElem.html();
                var newHtml  = textHtml.replace(/\r?\n|\r/g, '
');

                textElem.html( newHtml );

                return;
            },

            // Overrides Base
            _getViewOptions: function() {
                var self = this;
                var role_desc;

                switch ( self.options.index ) {
                    case 'P': role_desc = '';              break;
                    case 'C': role_desc = ' (Conclusion)'; break;
                    default : role_desc = ' (Premise)';    break;
                }

                var viewOptions = {
                    partial_sha1: self.options.sha1.substr(0, 20),
                    proposition_desc: 'Proposition' + role_desc,
                    details_desc: 'Proposition details\r\nSHA1: ' + self.options.sha1
                }
                return $.extend( viewOptions, self.options );
            }
        }
    } );

    return Proposition;
} );
<|endoftext|>


<commit_before>var Async = require('async');
var Mongoose = require('mongoose');
var BodyParser = require('body-parser');
var PathToRegexp = require('path-to-regexp');

var Definition = module.exports = function(api, label, model) {
  this.api = api;
  this.label = label;
  this.db = model;
}

var METHODS = ['get', 'patch', 'put', 'post', 'delete'];
var TO_OBJ_OPTIONS = {
  versionKey: false,
  setters: true,
  getters: true,
  virtuals: false,
}

Definition.prototype.queryDB = function(method, many, query, doc, options, callback) {
  var self = this;
  if (method === 'get') {
    var find = many ? self.db.find : self.db.findOne;
    find.apply(self.db, [query]).select(options.select || '').populate(options.populate || '').exec(callback);
  } else if (method === 'post') {
    var docs = many ? doc : [doc];
    Async.parallel(docs.map(function(doc) {
      return function(callback) {
        var toAdd = new self.db(doc);
        toAdd.save(function(err, newDoc) {
          callback(err, newDoc);
        });
      }
    }), function(err, results) {
      callback(err, many ? results : results[0]);
    })
  } else if (method === 'put') {
    var docs = many ? doc : [doc];
    Async.parallel(docs.map(function(doc) {
      return function(callback) {
        self.db.findOneAndUpdate(query, doc, {upsert: true, new: true}).exec(callback);
      }
    }), function(err, docs) {
      if (!err && !many) docs = docs[0];
      callback(err, docs)
    });
  } else if (method === 'patch') {
    if (many) {
      self.db.update(query, doc, {multi: true}).exec(function(err) {
        callback(err, {success: true});
      })
    } else {
      self.db.findOneAndUpdate(query, doc, {new: true}).exec(callback);
    }
  } else if (method === 'delete') {
    var remove = many ? self.db.remove : self.db.findOneAndRemove;
    remove.apply(self.db, [query]).exec(function(err, thing) {
      callback(err, thing);
    })
  } else {
    throw new Error("Unsupported method:" + method);
  }
}

var getRouteFunction = function(method, many) {
  // Can be called with (path[, middleware...]) or (req, res, callback);
  return function() {
    var self = this;
    arguments = Array.prototype.slice.call(arguments);
    var isMiddleware = typeof arguments[0] !== 'string';
    var sendResponse = !isMiddleware || arguments.length === 2;
    var options = sendResponse && typeof arguments[1] === 'object' ? arguments[1] : {};
    var dbAction = function(req, res, next) {
      var useMethod = isMiddleware ? method : req.jammin.method;
      self.queryDB(useMethod, many, req.jammin.query, req.jammin.document, options, function(err, thing) {
        if (err) res.status(500).json({error: err.toString()});
        else if (!thing) res.status(404).json({error: 'Not Found'})
        else if (sendResponse && (useMethod === 'get' || useMethod === 'post' || useMethod === 'put')) {
          if (many) thing = thing.map(function(t) { return t.toObject(TO_OBJ_OPTIONS) });
          else thing = thing.toObject(TO_OBJ_OPTIONS);
          if (options.mapItem) {
            if (many) thing = thing.map(options.mapItem);
            else thing = options.mapItem(thing);
          }
          res.json(thing);
        }
        else if (sendResponse) return res.json({success: true})
        else next(thing);
      })
    }
    // If we get (req, res, callback) instead of a path, just apply
    // dbAction. Otherwise delegate to the router.
    if (isMiddleware) return dbAction.apply(self, arguments);

    arguments = Array.prototype.slice.call(arguments);
    var expressPath = arguments[0];
    var keys = [];
    PathToRegexp(expressPath, keys);
    var swaggerPath = expressPath;
    keys.forEach(function(key) {
      swaggerPath = swaggerPath.replace(':' + key.name, '{' + key.name + '}');
    });
    var middleware = arguments.splice(1);
    if (typeof middleware[0] === 'object') middleware.shift();
    if (options.swagger) options.swagger = JSON.parse(JSON.stringify(options.swagger));
    self.api.swaggerBuilder.addRoute({
      method: method,
      path: swaggerPath,
      collection: self.label,
      many: many
    }, options.swagger);
    middleware.push(dbAction);
    middleware.unshift(expressPath);
    this.api.router[method].apply(this.api.router, middleware);
  }
}

METHODS.forEach(function(method) {
  Definition.prototype[method] = getRouteFunction(method);
  Definition.prototype[method + 'Many'] = getRouteFunction(method, true)
})
<commit_msg>add limit, sort, and skip<commit_after>var Async = require('async');
var Mongoose = require('mongoose');
var BodyParser = require('body-parser');
var PathToRegexp = require('path-to-regexp');

var Definition = module.exports = function(api, label, model) {
  this.api = api;
  this.label = label;
  this.db = model;
}

var METHODS = ['get', 'patch', 'put', 'post', 'delete'];
var TO_OBJ_OPTIONS = {
  versionKey: false,
  setters: true,
  getters: true,
  virtuals: false,
}

Definition.prototype.queryDB = function(method, many, jammin, options, callback) {
  var self = this;
  var query = jammin.query;
  var doc = jammin.document;
  if (method === 'get') {
    var find = many ? self.db.find : self.db.findOne;
    var run = find.apply(self.db, [query]).select(options.select || '').populate(options.populate || '');
    if (jammin.sort) run.sort(jammin.sort);
    if (jammin.limit) run.limit(jammin.limit);
    if (jammin.skip) run.skip(jammin.skip);
    run.exec(callback);
  } else if (method === 'post') {
    var docs = many ? doc : [doc];
    Async.parallel(docs.map(function(doc) {
      return function(callback) {
        var toAdd = new self.db(doc);
        toAdd.save(function(err, newDoc) {
          callback(err, newDoc);
        });
      }
    }), function(err, results) {
      callback(err, many ? results : results[0]);
    })
  } else if (method === 'put') {
    var docs = many ? doc : [doc];
    Async.parallel(docs.map(function(doc) {
      return function(callback) {
        self.db.findOneAndUpdate(query, doc, {upsert: true, new: true}).exec(callback);
      }
    }), function(err, docs) {
      if (!err && !many) docs = docs[0];
      callback(err, docs)
    });
  } else if (method === 'patch') {
    if (many) {
      self.db.update(query, doc, {multi: true}).exec(function(err) {
        callback(err, {success: true});
      })
    } else {
      self.db.findOneAndUpdate(query, doc, {new: true}).exec(callback);
    }
  } else if (method === 'delete') {
    var remove = many ? self.db.remove : self.db.findOneAndRemove;
    remove.apply(self.db, [query]).exec(function(err, thing) {
      callback(err, thing);
    })
  } else {
    throw new Error("Unsupported method:" + method);
  }
}

var getRouteFunction = function(method, many) {
  // Can be called with (path[, middleware...]) or (req, res, callback);
  return function() {
    var self = this;
    arguments = Array.prototype.slice.call(arguments);
    var isMiddleware = typeof arguments[0] !== 'string';
    var sendResponse = !isMiddleware || arguments.length === 2;
    var options = sendResponse && typeof arguments[1] === 'object' ? arguments[1] : {};
    var dbAction = function(req, res, next) {
      var useMethod = isMiddleware ? method : req.jammin.method;
      self.queryDB(useMethod, many, req.jammin, options, function(err, thing) {
        if (err) res.status(500).json({error: err.toString()});
        else if (!thing) res.status(404).json({error: 'Not Found'})
        else if (sendResponse && (useMethod === 'get' || useMethod === 'post' || useMethod === 'put')) {
          if (many) thing = thing.map(function(t) { return t.toObject(TO_OBJ_OPTIONS) });
          else thing = thing.toObject(TO_OBJ_OPTIONS);
          if (options.mapItem) {
            if (many) thing = thing.map(options.mapItem);
            else thing = options.mapItem(thing);
          }
          res.json(thing);
        }
        else if (sendResponse) return res.json({success: true})
        else next(thing);
      })
    }
    // If we get (req, res, callback) instead of a path, just apply
    // dbAction. Otherwise delegate to the router.
    if (isMiddleware) return dbAction.apply(self, arguments);

    arguments = Array.prototype.slice.call(arguments);
    var expressPath = arguments[0];
    var keys = [];
    PathToRegexp(expressPath, keys);
    var swaggerPath = expressPath;
    keys.forEach(function(key) {
      swaggerPath = swaggerPath.replace(':' + key.name, '{' + key.name + '}');
    });
    var middleware = arguments.splice(1);
    if (typeof middleware[0] === 'object') middleware.shift();
    if (options.swagger) options.swagger = JSON.parse(JSON.stringify(options.swagger));
    self.api.swaggerBuilder.addRoute({
      method: method,
      path: swaggerPath,
      collection: self.label,
      many: many
    }, options.swagger);
    middleware.push(dbAction);
    middleware.unshift(expressPath);
    this.api.router[method].apply(this.api.router, middleware);
  }
}

METHODS.forEach(function(method) {
  Definition.prototype[method] = getRouteFunction(method);
  Definition.prototype[method + 'Many'] = getRouteFunction(method, true)
})
<|endoftext|>


<commit_before>(function(koolchart) {
	var colors = ['#7CB5EC', '#434348', '#90ED7D', '#F7A35C'];

	koolchart.buildLayout = function(dataSeries) {
		var layoutStr =
			'<KoolChart backgroundColor="0xFFFFFF" borderStyle="none">'
				+'<Options>'
					+'<Caption text="Monthly Average Temperature"/>'
					+'<SubCaption text="Source: WorldClimate.com"/>'
				+'</Options>'
				+'<Line2DChart showDataTips="true" selectionMode="single">'
					+'<verticalAxis>'
						+'<LinearAxis id="vAxis"/>'
					+'</verticalAxis>'
					+'<horizontalAxis>'
						+'<CategoryAxis categoryField="Month"/>'
					+'</horizontalAxis>'
					+'<series>';

		for (var i = 0; i < dataSeries.length; i++) {
			var lineLayout = '<Line2DSeries id="series' + i + '" labelPosition="up" yField="Data' + i + '" raidus="4" displayName="' + dataSeries[i].name + '" itemRenderer="CircleItemRenderer">'
								+'<lineStroke>'
									+'<Stroke color="' + colors[i] + '" weight="3"/>'
								+'</lineStroke>'
								+'<fill>'
									+'<SolidColor color="' + colors[i] + '"/>'
								+'</fill>'
							+'</Line2DSeries>'
			layoutStr += lineLayout;
		}

		layoutStr += '</series>'
					+'<verticalAxisRenderers>'
						+'<Axis2DRenderer axis="{vAxis}" placement="left">'
							+'<axisStroke>'
								+'<Stroke color="#fd848f" weight="4"/>'
							+'</axisStroke>'
						+'</Axis2DRenderer>'
					+'</verticalAxisRenderers>'
					+'<backgroundElements>'
						+'<GridLines/>'
					+'</backgroundElements>'
				+'</Line2DChart>'
				+'<Box horizontalAlign="center" width="100%">'
        			+'<SubLegend useVisibleCheck="true" direction="horizontal" markerHeight="15" markerWidth="15">'

        for (var i = 0; i < dataSeries.length; i++) {
        	layoutStr += '<CheckableLegendItem targetSeries="{series' + i + '}" fill="' + colors[i] + '" label="' + dataSeries[i].name + '"/>'
        }

        layoutStr += '</SubLegend>'
    			+'</Box>'
			+'</KoolChart>';

		return layoutStr;
	};

	koolchart.formatData = function(xAxis, dataSeries) {
		var chartData = new Array();
		for (var i = 0; i < xAxis.length; i++) {
			var item = {'Month':xAxis[i]};
			for (var j = 0; j < dataSeries.length; j++) {
				item['Data' + j] = dataSeries[j].data[i];
			}
			chartData.push(item);
		}
		return chartData;
	};
})(window.koolchart = window.koolchart || {});

function renderLineWithKoolChart(divId, xAxis, dataSeries) {
	var chartVars = "KoolOnLoadCallFunction=chartReadyHandler";

	this.chartReadyHandler = function(id) {
		document.getElementById(id).setLayout(koolchart.buildLayout(dataSeries));
		document.getElementById(id).setData(koolchart.formatData(xAxis, dataSeries));
	};

	KoolChart.create("chart1", divId, chartVars, "100%", "100%");
}<commit_msg>Hide chunky data labels in KoolChart sample<commit_after>(function(koolchart) {
	var colors = ['#7CB5EC', '#434348', '#90ED7D', '#F7A35C'];

	koolchart.buildLayout = function(dataSeries) {
		var layoutStr =
			'<KoolChart backgroundColor="0xFFFFFF" borderStyle="none">'
				+'<Options>'
					+'<Caption text="Monthly Average Temperature"/>'
					+'<SubCaption text="Source: WorldClimate.com"/>'
				+'</Options>'
				+'<Line2DChart showDataTips="true" selectionMode="single">'
					+'<verticalAxis>'
						+'<LinearAxis id="vAxis"/>'
					+'</verticalAxis>'
					+'<horizontalAxis>'
						+'<CategoryAxis categoryField="Month"/>'
					+'</horizontalAxis>'
					+'<series>';

		for (var i = 0; i < dataSeries.length; i++) {
			var lineLayout = '<Line2DSeries id="series' + i + '" yField="Data' + i + '" raidus="4" displayName="' + dataSeries[i].name + '" itemRenderer="CircleItemRenderer">'
								+'<lineStroke>'
									+'<Stroke color="' + colors[i] + '" weight="3"/>'
								+'</lineStroke>'
								+'<fill>'
									+'<SolidColor color="' + colors[i] + '"/>'
								+'</fill>'
							+'</Line2DSeries>'
			layoutStr += lineLayout;
		}

		layoutStr += '</series>'
					+'<verticalAxisRenderers>'
						+'<Axis2DRenderer axis="{vAxis}" placement="left">'
							+'<axisStroke>'
								+'<Stroke color="#fd848f" weight="4"/>'
							+'</axisStroke>'
						+'</Axis2DRenderer>'
					+'</verticalAxisRenderers>'
					+'<backgroundElements>'
						+'<GridLines/>'
					+'</backgroundElements>'
				+'</Line2DChart>'
				+'<Box horizontalAlign="center" width="100%">'
        			+'<SubLegend useVisibleCheck="true" direction="horizontal" markerHeight="15" markerWidth="15">'

        for (var i = 0; i < dataSeries.length; i++) {
        	layoutStr += '<CheckableLegendItem targetSeries="{series' + i + '}" fill="' + colors[i] + '" label="' + dataSeries[i].name + '"/>'
        }

        layoutStr += '</SubLegend>'
    			+'</Box>'
			+'</KoolChart>';

		return layoutStr;
	};

	koolchart.formatData = function(xAxis, dataSeries) {
		var chartData = new Array();
		for (var i = 0; i < xAxis.length; i++) {
			var item = {'Month':xAxis[i]};
			for (var j = 0; j < dataSeries.length; j++) {
				item['Data' + j] = dataSeries[j].data[i];
			}
			chartData.push(item);
		}
		return chartData;
	};
})(window.koolchart = window.koolchart || {});

function renderLineWithKoolChart(divId, xAxis, dataSeries) {
	var chartVars = "KoolOnLoadCallFunction=chartReadyHandler";

	this.chartReadyHandler = function(id) {
		document.getElementById(id).setLayout(koolchart.buildLayout(dataSeries));
		document.getElementById(id).setData(koolchart.formatData(xAxis, dataSeries));
	};

	KoolChart.create("chart1", divId, chartVars, "100%", "100%");
}<|endoftext|>


<commit_before>/**
 * Using Rails-like standard naming convention for endpoints.
 * GET     /wishItem              ->  index
 * POST    /wishItem              ->  create
 * GET     /wishItem/:id          ->  show
 * PUT     /wishItem/:id          ->  update
 * DELETE  /wishItem/:id          ->  destroy
 */

'use strict';

var _ = require('lodash');
var WishItem = require('./wishItem.model');
var Thing = require('../thing/thing.model');

// Get list of wishItem
exports.index = function(req, res) {
  var listType = req.query.listType;
  // Request db
  if (listType === "outstanding") {
    WishItem.find({hasBrought: false}).
    populate('requestUsers[0].userId').
    populate('thing').
    exec(function (err, docs) {
      handleGetWishItems(err, docs, req, res);
    });

  } else if (listType === "history") {
    WishItem.find({hasBrought: true}).
    populate('requestUsers[0].userId').
    populate('thing').
    exec(function (err, docs) {
      handleGetWishItems(err, docs, req, res);
    });

  } else if (listType === "all") {
    WishItem.find({}).
    populate('requestUsers[0].userId').
    populate('thing').
    exec(function (err, docs) {
      handleGetWishItems(err, docs, req, res);
    });

  }
  // WishItem.find(function (err, wishItems) {
  //   if(err) { return handleError(res, err); }
  //   return res.json(200, wishItems);
  // });
};

function handleGetWishItems(err, wishItems, req, res) {
  if(err) { return handleError(res, err); }

  var jsonItems = [];

  var wishItemsLength = wishItems.length;
  for (var i = 0; i < wishItemsLength; i++) {
    var wishItem = wishItems[i];
    var thing = wishItem.thing;

    var likedByUserIds = thing.likedByUserIds;
    var liked = likedByUserIds.indexOf(req.user._id) !== -1;

    jsonItems[i] =
    {
      "_id": wishItem._id,
      "itemId": thing._id,
      "name": thing.name,
      "quantity": wishItem.requireQuantity,
      "hasBrought": wishItem.hasBrought,
      "buyRepetition": thing.buyRepetition,
      "liked": liked,
      "snackImageUrl": thing.snackImageUrl,
      "price": thing.price,
      "requesterName": wishItem.requestUsers[0].userId.name,
      "availableLocations": thing.availableLocations
    };
  } // End of for loop

  var result = {"wishItems": jsonItems};
  return res.status(200).json(result);
}

// Get a single wishItem
exports.show = function(req, res) {
  WishItem.findById(req.params.id, function (err, wishItem) {
    if(err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }
    return res.json(wishItem);
  });
};

// Creates a new wishItem in the DB.
exports.create = function(req, res) {

  var snackName = req.body.name;
  var snackQuantity = req.body.quantity;
  var snackImageUrl = req.body.snackImageUrl;
  var snackPrice = req.body.price;
  var availableLocations = req.body.availableLocations;
  var requestUserId = req.user._id;

  // Check if snack has existed in db
  Thing.findOne({name: snackName}, function (err, thing) {
    if(err) { return handleError(res, err); }

    var objectIdOfThing;

    // Snack has already existed
    if (thing) {
      objectIdOfThing = thing._id;
      createNewWishItem(objectIdOfThing, requestUserId, snackQuantity, req, res);
    } else {
      // Snack not existed: create new snack
      var newThingJSON =
      {
        "name": snackName,
        "snackImageUrl": snackImageUrl,
        "price": snackPrice,
        "buyRepetition": 0,
        "noOfLikes": 0,
        "availableLocations": availableLocations
      };

      Thing.create(newThingJSON, function (err, newThing) {
        if(err) { return handleError(res, err); }
        objectIdOfThing = newThing._id;
        createNewWishItem(objectIdOfThing, requestUserId, snackQuantity, req, res);
      });
    }

  });
  // WishItem.create(req.body, function (err, wishItem) {
    // if(err) { return handleError(res, err); }
    // return res.json(201, wishItem);
  //   mongoose.model('thing').find()function()err, ;
  // });
};

function createNewWishItem(objectIdOfThing, requestUserId, snackQuantity, req, res) {
  // Create wish item
  var newWishItemJSON =
  {
    "thing": objectIdOfThing,
    "requestUsers":
    [{
      "userId": requestUserId,
      "requireQuantity": snackQuantity
    }],
    "hasBrought": false,
    "requireQuantity": snackQuantity
  };

  WishItem.create(newWishItemJSON, function (err, newWishItemJSON) {
    if(err) { return handleError(res, err); }
    return res.status(200).json({});
  });
}

// Mark wish item as brought
exports.markAsBrought = function(req, res) {
  var objectIds = req.body.objectIds;
  var updateData = {_id: {$in: objectIds}};

  WishItem.update(updateData,
    { hasBrought: true },
    { multi: true },
    function (err, raw) {
      if(err) { return handleError(res, err); }
      return res.status(200).json({});
  });

  // WishItem.findByIdAndUpdate(objectId, updateData, function(err, wishItem){
  //   if (err) { return handleError(res, err); }
  //   if(!wishItem) { return res.send(404); }
  //   return res.status(200).json(wishItem);
  // });
}

// Update quantity of a wishitem
exports.updateQuantity = function(req, res) {
  var objectId = req.body.objectId;
  var addOrMinus = req.body.addOrMinus;

  WishItem.findById(objectId, function (err, wishItem) {
    if(err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }

    // Get new quantity
    var quantity = wishItem.requireQuantity;
    if (addOrMinus === "add") {
      quantity++;
    } else {
      quantity--;
    }

    if (quantity <= 0) {
      // Delete item
      wishItem.remove(function (err, doc) {
        if(err) { return handleError(res, err); }
        return res.status(200).json({});
      });
    } else {
      // Update quanity of item
      wishItem.requireQuantity = quantity;
      wishItem.save(function (err) {
        if(err) { return handleError(res, err); }
        return res.status(200).json({});
      });
    }

  });

  // Delete item
  // if (quantity <= 0) {
  //   WishItem.findByIdAndRemove(objectId, function (err, doc){
  //     if(err) { return handleError(res, err); }
  //     return res.status(200).json({});
  //   });
  // } else {
  //   // Update quanity of item
  //   WishItem.findByIdAndUpdate(objectId, {requireQuantity: quantity}, {"new": true}, function (err, doc){
  //     if(err) { return handleError(res, err); }
  //     return res.status(200).json(doc);
  //   });
  // }
}

// Updates an existing wishItem in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  WishItem.findById(req.params.id, function (err, wishItem) {
    if (err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }
    var updated = _.merge(wishItem, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, wishItem);
    });
  });
};

// Deletes a wishItem from the DB.
exports.destroy = function(req, res) {
  WishItem.findById(req.params.id, function (err, wishItem) {
    if(err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }
    wishItem.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}<commit_msg>add request time checker<commit_after>/**
 * Using Rails-like standard naming convention for endpoints.
 * GET     /wishItem              ->  index
 * POST    /wishItem              ->  create
 * GET     /wishItem/:id          ->  show
 * PUT     /wishItem/:id          ->  update
 * DELETE  /wishItem/:id          ->  destroy
 */

'use strict';

var _ = require('lodash');
var WishItem = require('./wishItem.model');
var Thing = require('../thing/thing.model');

// Get list of wishItem
exports.index = function(req, res) {
  var listType = req.query.listType;
  // Request db
  if (listType === "outstanding") {
    WishItem.find({hasBrought: false}).
    populate('requestUsers[0].userId').
    populate('thing').
    exec(function (err, docs) {
      handleGetWishItems(err, docs, req, res);
    });

  } else if (listType === "history") {
    WishItem.find({hasBrought: true}).
    populate('requestUsers[0].userId').
    populate('thing').
    exec(function (err, docs) {
      handleGetWishItems(err, docs, req, res);
    });

  } else if (listType === "all") {
    WishItem.find({}).
    populate('requestUsers[0].userId').
    populate('thing').
    exec(function (err, docs) {
      handleGetWishItems(err, docs, req, res);
    });

  }
  // WishItem.find(function (err, wishItems) {
  //   if(err) { return handleError(res, err); }
  //   return res.json(200, wishItems);
  // });
};

function handleGetWishItems(err, wishItems, req, res) {
  if(err) { return handleError(res, err); }

  var jsonItems = [];

  var wishItemsLength = wishItems.length;
  for (var i = 0; i < wishItemsLength; i++) {
    var wishItem = wishItems[i];
    var thing = wishItem.thing;

    var likedByUserIds = thing.likedByUserIds;
    var liked = likedByUserIds.indexOf(req.user._id) !== -1;

    jsonItems[i] =
    {
      "_id": wishItem._id,
      "itemId": thing._id,
      "name": thing.name,
      "quantity": wishItem.requireQuantity,
      "hasBrought": wishItem.hasBrought,
      "buyRepetition": thing.buyRepetition,
      "likes": thing.likedByUserIds.length || 0,
      "liked": liked,
      "snackImageUrl": thing.snackImageUrl,
      "price": thing.price,
      "requesterName": wishItem.requestUsers[0].userId.name,
      "availableLocations": thing.availableLocations
    };
  } // End of for loop

  var result = {"wishItems": jsonItems};
  return res.status(200).json(result);
}

// Get a single wishItem
exports.show = function(req, res) {
  WishItem.findById(req.params.id, function (err, wishItem) {
    if(err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }
    return res.json(wishItem);
  });
};

// Creates a new wishItem in the DB.
exports.create = function(req, res) {

  var snackName = req.body.name;
  var snackQuantity = req.body.quantity;
  var snackImageUrl = req.body.snackImageUrl;
  var snackPrice = req.body.price;
  var availableLocations = req.body.availableLocations;
  var requestUserId = req.user._id;

  // Check if snack has existed in db
  Thing.findOne({name: snackName}, function (err, thing) {
    if(err) { return handleError(res, err); }

    var objectIdOfThing;

    // Snack has already existed
    if (thing) {
      objectIdOfThing = thing._id;
      createNewWishItem(objectIdOfThing, requestUserId, snackQuantity, req, res);
    } else {
      // Snack not existed: create new snack
      var newThingJSON =
      {
        "name": snackName,
        "snackImageUrl": snackImageUrl,
        "price": snackPrice,
        "buyRepetition": 0,
        "noOfLikes": 0,
        "availableLocations": availableLocations
      };

      Thing.create(newThingJSON, function (err, newThing) {
        if(err) { return handleError(res, err); }
        objectIdOfThing = newThing._id;
        createNewWishItem(objectIdOfThing, requestUserId, snackQuantity, req, res);
      });
    }

  });
  // WishItem.create(req.body, function (err, wishItem) {
    // if(err) { return handleError(res, err); }
    // return res.json(201, wishItem);
  //   mongoose.model('thing').find()function()err, ;
  // });
};

function createNewWishItem(objectIdOfThing, requestUserId, snackQuantity, req, res) {
  // Create wish item
  var newWishItemJSON =
  {
    "thing": objectIdOfThing,
    "requestUsers":
    [{
      "userId": requestUserId,
      "requireQuantity": snackQuantity
    }],
    "hasBrought": false,
    "requireQuantity": snackQuantity
  };

  WishItem.create(newWishItemJSON, function (err, newWishItemJSON) {
    if(err) { return handleError(res, err); }
    return res.status(200).json({});
  });
}

// Mark wish item as brought
exports.markAsBrought = function(req, res) {
  var objectIds = req.body.objectIds;
  var updateData = {_id: {$in: objectIds}};

  WishItem.update(updateData,
    { hasBrought: true },
    { multi: true },
    function (err, noOfWishItemsUpdated) {
      WishItem.
        find(updateData).
        select('thing -_id').
        lean().
        exec(function(err, items) {
          if(err) { console.log('err', err); }
          var query = {_id: {$in:[]}};
          for (var i = 0; i < items.length; i++) {
            query._id.$in.push(items[i].thing.toString());
          }
          Thing.update(query,
            { $inc: {buyRepetition : 1}},
            { multi: true },
            function (err, noOfItemsUpdated) {
              if(err) { return handleError(res, err); }
              return res.status(200).json({});
          });
        });
  });

  // WishItem.findByIdAndUpdate(objectId, updateData, function(err, wishItem){
  //   if (err) { return handleError(res, err); }
  //   if(!wishItem) { return res.send(404); }
  //   return res.status(200).json(wishItem);
  // });
}

// Update quantity of a wishitem
exports.updateQuantity = function(req, res) {
  var objectId = req.body.objectId;
  var addOrMinus = req.body.addOrMinus;

  WishItem.findById(objectId, function (err, wishItem) {
    if(err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }

    // Get new quantity
    var quantity = wishItem.requireQuantity;
    if (addOrMinus === "add") {
      quantity++;
    } else {
      quantity--;
    }

    if (quantity <= 0) {
      // Delete item
      wishItem.remove(function (err, doc) {
        if(err) { return handleError(res, err); }
        return res.status(200).json({});
      });
    } else {
      // Update quanity of item
      wishItem.requireQuantity = quantity;
      wishItem.save(function (err) {
        if(err) { return handleError(res, err); }
        return res.status(200).json({});
      });
    }

  });

  // Delete item
  // if (quantity <= 0) {
  //   WishItem.findByIdAndRemove(objectId, function (err, doc){
  //     if(err) { return handleError(res, err); }
  //     return res.status(200).json({});
  //   });
  // } else {
  //   // Update quanity of item
  //   WishItem.findByIdAndUpdate(objectId, {requireQuantity: quantity}, {"new": true}, function (err, doc){
  //     if(err) { return handleError(res, err); }
  //     return res.status(200).json(doc);
  //   });
  // }
}

// Updates an existing wishItem in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  WishItem.findById(req.params.id, function (err, wishItem) {
    if (err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }
    var updated = _.merge(wishItem, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, wishItem);
    });
  });
};

// Deletes a wishItem from the DB.
exports.destroy = function(req, res) {
  WishItem.findById(req.params.id, function (err, wishItem) {
    if(err) { return handleError(res, err); }
    if(!wishItem) { return res.send(404); }
    wishItem.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}

<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const webpack = require('webpack');
const validator = require('webpack-validator');

module.exports = validator({
  entry: path.join(__dirname, 'src', 'js', 'index.js'),

  output: {
    path: path.join(__dirname, 'build', 'js'),
    filename: 'main.min.js'
  },

  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),

    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': '"production"'
      }
    })
  ],

  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel',
      exclude: /node_modules|src\/server/,
      include: /src/
    }]
  },

  resolve: {
    alias: {
      'react': 'preact-compat',
      'react-dom': 'preact-compat'
    }
  }

});
<commit_msg>Change Preact from React :(<commit_after>'use strict';

const path = require('path');
const webpack = require('webpack');
const validator = require('webpack-validator');

module.exports = validator({
  entry: path.join(__dirname, 'src', 'js', 'index.js'),

  output: {
    path: path.join(__dirname, 'build', 'js'),
    filename: 'main.min.js'
  },

  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),

    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': '"production"'
      }
    })
  ],

  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel',
      exclude: /node_modules|src\/server/,
      include: /src/
    }]
  }
  // ,

  // resolve: {
  //   alias: {
  //     'react': 'preact-compat',
  //     'react-dom': 'preact-compat'
  //   }
  // }

});
<|endoftext|>


<commit_before>import React from 'react';
import {Form, Input, Radio} from 'antd';
import {config} from '../../../common';
import styles from './Hypertension.less';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

function Diabetes( props ) {
	const { getFieldDecorator } = props.form;
	return (

需求说明

				<FormItem {...config.formItemLayout} label="随访方案">
					{getFieldDecorator( 'interviewScheme', {
						initialValue: props.interviewScheme ? parseInt( props.interviewScheme ) : 1
					} )(
						<RadioGroup disabled={props.disabled}>
							<Radio value={1}>方案一：协助医生随访糖尿病患者的体征、生活方式、辅助检查、用药情况</Radio>
							<Radio value={2}>方案二：协助医生随访糖尿病患者的症状</Radio>
							<Radio value={3}>方案三：协助医生随访糖尿病患者的血糖数值</Radio>
						</RadioGroup>
					)}
				</FormItem>
				<FormItem {...config.formItemLayout} label="要求">
					{getFieldDecorator( 'requirements', {
						initialValue: props.requirements,
					} )(
						<Input type="textarea" rows={8} placeholder="请输入您的其他要求" disabled={props.disabled}/>
					)}
				</FormItem>

	);
}

export default Form.create()( Diabetes );<commit_msg>need->update Diabetes.js<commit_after>import React from 'react';
import {Form, Input, Radio,Button,Modal} from 'antd';
import {config} from '../../../common';
import styles from './Diabetes.less';
import {DiabetesA,DiabetesB,DiabetesC} from '../../../components';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

function Diabetes( props ) {
	const { getFieldDecorator } = props.form;
  const size = "small";
  const text = "预览";
  const showPlan =(e) => {
    let plan=e.currentTarget.id;
    let planNode=<DiabetesA disabled={props.disabled}/>;
    let title= '方案1   (价格：暂未定价)';
    if("2"===plan){
      title= '方案2     (价格：暂未定价)';
      planNode=<DiabetesB disabled={props.disabled}/>;
    }else if("3"===plan){
      title= '方案3     (价格：暂未定价)';
      planNode=<DiabetesC disabled={props.disabled}/>;
    }
    Modal.info({
      title: title,
      visible: true,
      content: (
        planNode
      ),
      width: '1100',
      onOk() {
      },
    });
  }

	return (

需求说明

				<FormItem {...config.formItemLayout} label="随访方案">
					{getFieldDecorator( 'interviewScheme', {
						initialValue: props.interviewScheme ? parseInt( props.interviewScheme ) : 1
					} )(
						<RadioGroup disabled={props.disabled}>
							<Radio value={1}>方案一：协助医生随访糖尿病患者的体征、生活方式、辅助检查、用药情况</Radio>
              <Button type="primary"size={size}   icon="play-circle"   id={1}  onClick={showPlan}>{text}</Button>

							<Radio value={2}>方案二：协助医生随访糖尿病患者的症状</Radio>
              <Button type="primary" size={size}  icon="play-circle"  id={2}  onClick={showPlan}>{text}</Button>

							<Radio value={3}>方案三：协助医生随访糖尿病患者的血糖数值</Radio>
              <Button type="primary" size={size}  icon="play-circle"  id={3} onClick={showPlan}>{text}</Button>

						</RadioGroup>
					)}
				</FormItem>
				<FormItem {...config.formItemLayout} label="要求">
					{getFieldDecorator( 'requirements', {
						initialValue: props.requirements,
					} )(
						<Input type="textarea" rows={8} placeholder="请输入您的其他要求" disabled={props.disabled}/>
					)}
				</FormItem>

	);
}

export default Form.create()( Diabetes );
<|endoftext|>