<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  getBlankQuest,
  getQuestFromProps,
  getQuizStatefromQuest
} from '../../libs/quizHelper'
import RaisedButton from 'material-ui/RaisedButton'
import TextField from 'material-ui/TextField'
import Snackbar from 'material-ui/Snackbar'

class QuizInput extends Component {
  constructor (props, context) {
    super(props, context)
    let quest = getQuestFromProps(props.quest)
    this.state = getQuizStatefromQuest(quest)
  }

  handleSubmit = e => {
    const { newQuiz, onSave } = this.props

    // Save quiz
    const { subject, question, choice_0, choice_1, choice_2 } = this.state
    onSave({ subject, question, choice_0, choice_1, choice_2 })

    if (newQuiz) {
      this.setState(getBlankQuest())
    }
  }

  handleChange = e => {
    this.setState({ [e.target.name]: e.target.value })
  }

  handleDoubleClick = form => {
    this.setState({ isEditing: { [form]: true } })
  }

  handleBlur = form => {
    const { newQuiz, onSave } = this.props
    if (!newQuiz) {
      let keys = form.split('_')
      let quiz = keys[0] === 'choice'
        ? { [keys[1]]: this.state[form] }
        : { [form]: this.state[form] }
      let isChoice = keys[0] === 'choice'
      onSave(quiz, isChoice)
      this.setState({ isEditing: { [form]: false } })
    }
  }

  handleRequestClose = () => {
    this.setState({
      open: false
    })
  }

  renderForm (form, autoFocus) {
    const { newQuiz } = this.props
    const getFloatingLabelText = form => {
      switch (form) {
        case 'choice_0':
          return 'Answer'
        case 'choice_1':
          return 'Choice 1'
        case 'choice_2':
          return 'Choice 2'
        default:
          return form
      }
    }

    if (this.state.isEditing[form] || newQuiz) {
      return (

          <TextField
            ref={form}
            type='text'
            name={form}
            floatingLabelText={getFloatingLabelText(form)}
            // defaultValue={this.state[form]}
            value={this.state[form]}
            autoFocus={autoFocus || this.state.isEditing[form]}
            onChange={this.handleChange}
            onBlur={() => this.handleBlur(form)}
          />

      )
    } else {
      return (

           this.handleDoubleClick(form)}>
            {getFloatingLabelText(form)}: {this.state[form]}

      )
    }
  }

  renderSubmitButton () {
    const { newQuiz } = this.props
    if (newQuiz) {
      return (

          <RaisedButton
            type='submit'
            label='Submit'
            primary
            onTouchTap={this.handleSubmit}
          />
          <Snackbar
            open={this.state.open}
            message='Quiz added'
            autoHideDuration={4000}
            onRequestClose={this.handleRequestClose}
          />

      )
    }
  }

  render () {
    const { idx, newQuiz } = this.props
    const autoFocus = true
    return (

        {idx &&
#{idx}
}
        {this.renderForm('subject', autoFocus)}
        {this.renderForm('question')}
        {this.renderForm('choice_0')}
        {this.renderForm('choice_1')}
        {this.renderForm('choice_2')}
        {newQuiz && this.renderSubmitButton()}

    )
  }
}

QuizInput.propTypes = {
  idx: PropTypes.number,
  onSave: PropTypes.func.isRequired,
  quest: PropTypes.object,
  newQuiz: PropTypes.bool
}

export default QuizInput
<commit_msg>Add case in getFloatingLabelText<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {
  getBlankQuest,
  getQuestFromProps,
  getQuizStatefromQuest
} from '../../libs/quizHelper'
import RaisedButton from 'material-ui/RaisedButton'
import TextField from 'material-ui/TextField'
import Snackbar from 'material-ui/Snackbar'

class QuizInput extends Component {
  constructor (props, context) {
    super(props, context)
    let quest = getQuestFromProps(props.quest)
    this.state = getQuizStatefromQuest(quest)
  }

  handleSubmit = e => {
    const { newQuiz, onSave } = this.props

    // Save quiz
    const { subject, question, choice_0, choice_1, choice_2 } = this.state
    onSave({ subject, question, choice_0, choice_1, choice_2 })

    if (newQuiz) {
      this.setState(getBlankQuest())
    }
  }

  handleChange = e => {
    this.setState({ [e.target.name]: e.target.value })
  }

  handleDoubleClick = form => {
    this.setState({ isEditing: { [form]: true } })
  }

  handleBlur = form => {
    const { newQuiz, onSave } = this.props
    if (!newQuiz) {
      let keys = form.split('_')
      let quiz = keys[0] === 'choice'
        ? { [keys[1]]: this.state[form] }
        : { [form]: this.state[form] }
      let isChoice = keys[0] === 'choice'
      onSave(quiz, isChoice)
      this.setState({ isEditing: { [form]: false } })
    }
  }

  handleRequestClose = () => {
    this.setState({
      open: false
    })
  }

  renderForm (form, autoFocus) {
    const { newQuiz } = this.props
    const getFloatingLabelText = form => {
      switch (form) {
        case 'subject':
          return 'Subject'
        case 'question':
          return 'Question'
        case 'choice_0':
          return 'Answer'
        case 'choice_1':
          return 'Choice 1'
        case 'choice_2':
          return 'Choice 2'
        default:
          return form
      }
    }

    if (this.state.isEditing[form] || newQuiz) {
      return (

          <TextField
            ref={form}
            type='text'
            name={form}
            floatingLabelText={getFloatingLabelText(form)}
            // defaultValue={this.state[form]}
            value={this.state[form]}
            autoFocus={autoFocus || this.state.isEditing[form]}
            onChange={this.handleChange}
            onBlur={() => this.handleBlur(form)}
          />

      )
    } else {
      return (

           this.handleDoubleClick(form)}>
            {getFloatingLabelText(form)}: {this.state[form]}

      )
    }
  }

  renderSubmitButton () {
    const { newQuiz } = this.props
    if (newQuiz) {
      return (

          <RaisedButton
            type='submit'
            label='Submit'
            primary
            onTouchTap={this.handleSubmit}
          />
          <Snackbar
            open={this.state.open}
            message='Quiz added'
            autoHideDuration={4000}
            onRequestClose={this.handleRequestClose}
          />

      )
    }
  }

  render () {
    const { idx, newQuiz } = this.props
    const autoFocus = true
    return (

        {idx &&
#{idx}
}
        {this.renderForm('subject', autoFocus)}
        {this.renderForm('question')}
        {this.renderForm('choice_0')}
        {this.renderForm('choice_1')}
        {this.renderForm('choice_2')}
        {newQuiz && this.renderSubmitButton()}

    )
  }
}

QuizInput.propTypes = {
  idx: PropTypes.number,
  onSave: PropTypes.func.isRequired,
  quest: PropTypes.object,
  newQuiz: PropTypes.bool
}

export default QuizInput
<|endoftext|>


<commit_before>(function() {

	var module = angular.module('brew-o-module.controller');

	module.controller("RecipeLogCtrl",function($scope,BrewCalc,BrewHelper,$timeout) {

        //Constantes (Esto tengo q poder configurarlo)
        var MASH_TEMP_TIME = $scope.recipe.timeWaterMash;
        var COOLING_TIME = $scope.recipe.coolingTime;

        $scope.discardFilter = {discard:false};
        $scope.isFiltering = true;

        $scope.toogleRemovedFilter = function() {
            if ( $scope.isFiltering ) {
                $scope.discardFilter = {};
                $scope.isFiltering = false;
            } else {
                $scope.discardFilter = {discard:false};
                $scope.isFiltering = true;
            }
        };

        $scope.removed = false;

        $scope.opened = false;
        $scope.openDp = function() {
            $timeout(function() {
                $scope.opened = true;
            });
        };

        $scope.edit = null;

        $scope.goEdit = function(log) {
            $scope.edit = log;
        };

        $scope.goNew = function() {
            var log = {
                time: new Date(),
                delay: 0,
                detail: null,
                logType: 'CUSTOM',
                discard: false
            };
            $scope.recipe.log.logs.push(log);
            $scope.goEdit(log);
            updatePendingTime();
        };

        $scope.orderLog = function(value) {
            if ( value.time instanceof Date ) {
                return value.time;
            } else {
                return new Date(value.time);
            }
        };

        $scope.now = function() {
            if ( $scope.recipe.log.logs.length != 0 ) {
                for ( var i=$scope.recipe.log.logs.length - 1; i>=0; i--) {
                    var log = $scope.recipe.log.logs[i];
                    if ( log.logType != 'CUSTOM') {
                        var time = log.time;
                        if ( typeof(time) == 'string') {
                            time = new Date(time);
                        }
                        return  time;
                    }
                }
                return new Date();
            } else {
                return new Date();
            }
        };

        var mashFixed = [{
            delay: 0,
            detail: 'Encender Fuego',
            logType: 'START'
        }];

        var spargeFixed = [{
            delay: $scope.recipe.spargeDuration,
            detail: 'Comenzar Lavado',
            logType: 'SPARGE'
        }, {
            delay: 60,
            detail: 'Finalizar Lavado',
            logType: 'SPARGE'
        }];

        var boilFixed = [{
            delay: $scope.recipe.preBoilTime,
            delayUnit: 'm',
            detail: 'Romper Hervor',
            logType: 'BOIL'
        }];

        var coolingFixed = [{
            delay: 0,
            delayUnit: 'm',
            detail: 'Apagar fuego y Whirpool',
            logType: 'COOLING'
        },{
            delay: 10,
            delayUnit: 'm',
            detail: 'Enfriado',
            logType: 'COOLING'
        }];

        function addMinutes(date, minutes) {
            var d = new Date(date.getTime());
            d.setMinutes(d.getMinutes()+minutes);
            return d;
        }

        function prevTime() {
            if ( $scope.pendingLogs.length != 0) {
                return $scope.pendingLogs[$scope.pendingLogs.length-1].time();
            } else {
                return $scope.now();
            }
        }

        function addFixed(list) {
            for (var i=0; i<list.length; i++) {
                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == list[i].logType ? 0 : -1;
                });
                if ( filter.length != 0 ) continue;

                addPending(list[i].delay,list[i].detail,list[i].logType);
            }
        }

        function stepAction (STEP) {
            if (STEP.infuse) {
                return "Agregar Agua"
            } else if (STEP.decoction) {
                return "Decoccion";
            }
            return null;
        }

        $scope.calculatePending = function() {
            $scope.pendingLogs = [];

            addFixed(mashFixed);
            var delay = MASH_TEMP_TIME;

            //add mash step
            for ( var i=0; i<$scope.recipe.MASH.MASH_STEPS.MASH_STEP.length; i ++ ) {
                step = $scope.recipe.MASH.MASH_STEPS.MASH_STEP[i];

                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == 'MASH_STEP' && item.logRef == step._id.toString() ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    delay = step.STEP_TIME;
                    continue;
                }

                var name = step.NAME + ' - ' + step.STEP_TEMP + 'ºC ';
                if ( step.END_TEMP != step.STEP_TEMP ) name += ' a ' + step.END_TEMP + 'ºC';
                name += ' - ' + step.STEP_TIME + ' min';
                if ( stepAction(step) ) name += ' - ' + stepAction(step);
                if ( step.recirculate ) name += ' - Recirculando';

                addPending(delay,name,'MASH_STEP',step._id.toString());
                delay = step.STEP_TIME;
            };
            //Sparge
            for (var i=0; i<spargeFixed.length; i++) {
                var f = spargeFixed[i];
                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == f.logType ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    delay = f.delay;
                    continue;
                }
                addPending(delay, f.detail, f.logType);
                delay = f.delay;
            };

            addFixed(boilFixed);
			for (var i=0; i<boilFixed.length; i++) {
				delay = boilFixed[i].delay;
			}

            var prevDelay = $scope.recipe.BOIL_TIME;
            //Hoping (exclud Dry-Hop)
            for( var i=0; i<$scope.recipe.HOPS.HOP.length; i++ ) {
                var hop = $scope.recipe.HOPS.HOP[i];
				if ( hop.USE !== 'Dry Hop') {
					var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
	                    return item.logType == 'BOIL_HOP' && item.logRef == hop._id.toString() ? 0 : -1;
	                });
					var hopTime;
					if ( hop.USE !== 'First Wort') {
						hopTime = hop.TIME;
					} else {
						hopTime = $scope.recipe.BOIL_TIME;
					}
	                if ( filter.length != 0 ) {
						prevDelay = hopTime;
	                    continue;
	                }
	                var name = hop.AMOUNT*1000 + 'g de ' + hop.NAME + ' (' + hop.USE + ' '+hop.TIME+'\')';
	                addPending(prevDelay - hopTime,name,'BOIL_HOP',hop._id.toString());
					prevDelay = hopTime;
				}
            }

			//add coling time for last hopping addiction
			coolingFixed[0].delay = prevDelay;
            addFixed(coolingFixed);

            //Hasta la inoculacion tomo el tiempo fijo de enfriado.
            prevDelay = COOLING_TIME;
            for( var i=0; i<$scope.recipe.fermentation.stages.length; i++ ) {
                var stage = $scope.recipe.fermentation.stages[i];

                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == 'FERM_STAGE' && item.logRef == stage._id.toString() ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    prevDelay = convert2Minutes(stage);
                    continue;
                }

                var name =  stage.title+' - '+stage.duration+' '+stage.durationMode;
                name += ' - '+stage.temperature+'º';
                if ( stage.temperature != stage.temperatureEnd) {
                	name += ' a '+stage.temperatureEnd+'º';
                }

                addPending(prevDelay,name,'FERM_STAGE',stage._id.toString());
                prevDelay = convert2Minutes(stage);
            }

			//Hoping (only Dry-Hop)
            for( var i=0; i<$scope.recipe.HOPS.HOP.length; i++ ) {
                var hop = $scope.recipe.HOPS.HOP[i];
				if ( hop.USE === 'Dry Hop') {
					var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
	                    return item.logType == 'BOIL_HOP' && item.logRef == hop._id.toString() ? 0 : -1;
	                });
	                if ( filter.length != 0 ) {
	                    prevDelay = hop.TIME;
	                    continue;
	                }
	                var name = hop.AMOUNT*1000 + 'g de ' + hop.NAME + ' (' + hop.USE + ' '+hop.TIME+'\')';
	                addPending(prevDelay - hop.TIME,name,'BOIL_HOP',hop._id.toString());
	                prevDelay = hop.TIME;
				}
            }

            //en prevDelay me queda ya cargado el timpo del ultimo paso de fermentacion.
            //Embotellado
            for( var i=0; i<$scope.recipe.bottling.bottles.length; i++ ) {
            	var bottle = $scope.recipe.bottling.bottles[i];

				var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == 'BOTTLING' && item.logRef == bottle._id.toString() ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    prevDelay = 0;
                    continue;
                }
                var name =  bottle.bottleType+' - '+bottle.amount+' Unidades';

                addPending(prevDelay,name,'BOTTLING',bottle._id.toString());
                prevDelay = 0;
            }

        };

        function convert2Minutes(stage) {
            if ( stage.durationMode =='Horas') {
                return stage.duration * 60;
            } else if ( stage.durationMode =='Dias') {
                return stage.duration * 60 * 24;
            }
        }

        function addPending(delay,detail,type,ref) {
            $scope.pendingLogs.push({
                prev: prevTime(),
                time: function() {
                    return addMinutes(this.prev,this.delay);
                },
                delay: delay,
                detail: detail,
                logType: type,
                logRef: ref
            });
        }

        $scope.calculatePending();

        function updatePendingTime() {
            if ( $scope.pendingLogs != 0 ) {
                $scope.pendingLogs[0].prev = $scope.now();
                for (var i=1; i<$scope.pendingLogs.length; i++) {
                    $scope.pendingLogs[i].prev = $scope.pendingLogs[i-1].time();
                }
            }
        }

        $scope.$watch("edit.time", function(value) {
            updatePendingTime();
        });

        $scope.pushAndEdit = function(log) {
        	$scope.push(log);
        	var last = $scope.recipe.log.logs[$scope.recipe.log.logs.length-1];
        	$scope.goEdit(last);
        };

        $scope.push = function(log) {
            log.time = new Date();
            $scope.recipe.log.logs.push({
                time: new Date(),
                delay: log.delay,
                detail: log.detail,
                logType: log.logType,
                logRef: log.logRef,
                discard: false
            });
            util.Arrays.remove($scope.pendingLogs,log);
            updatePendingTime();
        };

        $scope.discard = function(log) {
        	log.discard = true;
        };

        $scope.pushAndDiscard = function(log) {
        	$scope.push(log);
        	var last = $scope.recipe.log.logs[$scope.recipe.log.logs.length-1];
        	$scope.discard(last);
        };

		$scope.restoreAll = function() {
			$scope.recipe.log.logs = [];
			$scope.calculatePending();
		};

        /*
         * Remove Log from top, and put in down list again.
         */
        $scope.restore = function(log) {
        	util.Arrays.remove($scope.recipe.log.logs,log);
        	$scope.calculatePending();
        };
    });
})();
<commit_msg>fix bug for finish sparge in log<commit_after>(function() {

	var module = angular.module('brew-o-module.controller');

	module.controller("RecipeLogCtrl",function($scope,BrewCalc,BrewHelper,$timeout) {

        //Constantes (Esto tengo q poder configurarlo)
        var MASH_TEMP_TIME = $scope.recipe.timeWaterMash;
        var COOLING_TIME = $scope.recipe.coolingTime;

        $scope.discardFilter = {discard:false};
        $scope.isFiltering = true;

        $scope.toogleRemovedFilter = function() {
            if ( $scope.isFiltering ) {
                $scope.discardFilter = {};
                $scope.isFiltering = false;
            } else {
                $scope.discardFilter = {discard:false};
                $scope.isFiltering = true;
            }
        };

        $scope.removed = false;

        $scope.opened = false;
        $scope.openDp = function() {
            $timeout(function() {
                $scope.opened = true;
            });
        };

        $scope.edit = null;

        $scope.goEdit = function(log) {
            $scope.edit = log;
        };

        $scope.goNew = function() {
            var log = {
                time: new Date(),
                delay: 0,
                detail: null,
                logType: 'CUSTOM',
                discard: false
            };
            $scope.recipe.log.logs.push(log);
            $scope.goEdit(log);
            updatePendingTime();
        };

        $scope.orderLog = function(value) {
            if ( value.time instanceof Date ) {
                return value.time;
            } else {
                return new Date(value.time);
            }
        };

        $scope.now = function() {
            if ( $scope.recipe.log.logs.length != 0 ) {
                for ( var i=$scope.recipe.log.logs.length - 1; i>=0; i--) {
                    var log = $scope.recipe.log.logs[i];
                    if ( log.logType != 'CUSTOM') {
                        var time = log.time;
                        if ( typeof(time) == 'string') {
                            time = new Date(time);
                        }
                        return  time;
                    }
                }
                return new Date();
            } else {
                return new Date();
            }
        };

        var mashFixed = [{
            delay: 0,
            detail: 'Encender Fuego',
            logType: 'START'
        }];

        var spargeFixed = [{
            delay: $scope.recipe.spargeDuration,
            detail: 'Comenzar Lavado',
            logType: 'SPARGE_0'
        }, {
            delay: 60,
            detail: 'Finalizar Lavado',
            logType: 'SPARGE_1'
        }];

        var boilFixed = [{
            delay: $scope.recipe.preBoilTime,
            delayUnit: 'm',
            detail: 'Romper Hervor',
            logType: 'BOIL'
        }];

        var coolingFixed = [{
            delay: 0,
            delayUnit: 'm',
            detail: 'Apagar fuego y Whirpool',
            logType: 'COOLING'
        },{
            delay: 10,
            delayUnit: 'm',
            detail: 'Enfriado',
            logType: 'COOLING'
        }];

        function addMinutes(date, minutes) {
            var d = new Date(date.getTime());
            d.setMinutes(d.getMinutes()+minutes);
            return d;
        }

        function prevTime() {
            if ( $scope.pendingLogs.length != 0) {
                return $scope.pendingLogs[$scope.pendingLogs.length-1].time();
            } else {
                return $scope.now();
            }
        }

        function addFixed(list) {
            for (var i=0; i<list.length; i++) {
                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == list[i].logType ? 0 : -1;
                });
                if ( filter.length != 0 ) continue;

                addPending(list[i].delay,list[i].detail,list[i].logType);
            }
        }

        function stepAction (STEP) {
            if (STEP.infuse) {
                return "Agregar Agua"
            } else if (STEP.decoction) {
                return "Decoccion";
            }
            return null;
        }

        $scope.calculatePending = function() {
            $scope.pendingLogs = [];

            addFixed(mashFixed);
            var delay = MASH_TEMP_TIME;

            //add mash step
            for ( var i=0; i<$scope.recipe.MASH.MASH_STEPS.MASH_STEP.length; i ++ ) {
                step = $scope.recipe.MASH.MASH_STEPS.MASH_STEP[i];

                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == 'MASH_STEP' && item.logRef == step._id.toString() ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    delay = step.STEP_TIME;
                    continue;
                }

                var name = step.NAME + ' - ' + step.STEP_TEMP + 'ºC ';
                if ( step.END_TEMP != step.STEP_TEMP ) name += ' a ' + step.END_TEMP + 'ºC';
                name += ' - ' + step.STEP_TIME + ' min';
                if ( stepAction(step) ) name += ' - ' + stepAction(step);
                if ( step.recirculate ) name += ' - Recirculando';

                addPending(delay,name,'MASH_STEP',step._id.toString());
                delay = step.STEP_TIME;
            };
            //Sparge
            for (var i=0; i<spargeFixed.length; i++) {
                var f = spargeFixed[i];
                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == f.logType ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    delay = f.delay;
                    continue;
                }
                addPending(delay, f.detail, f.logType);
                delay = f.delay;
            };

            addFixed(boilFixed);
			for (var i=0; i<boilFixed.length; i++) {
				delay = boilFixed[i].delay;
			}

            var prevDelay = $scope.recipe.BOIL_TIME;
            //Hoping (exclud Dry-Hop)
            for( var i=0; i<$scope.recipe.HOPS.HOP.length; i++ ) {
                var hop = $scope.recipe.HOPS.HOP[i];
				if ( hop.USE !== 'Dry Hop') {
					var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
	                    return item.logType == 'BOIL_HOP' && item.logRef == hop._id.toString() ? 0 : -1;
	                });
					var hopTime;
					if ( hop.USE !== 'First Wort') {
						hopTime = hop.TIME;
					} else {
						hopTime = $scope.recipe.BOIL_TIME;
					}
	                if ( filter.length != 0 ) {
						prevDelay = hopTime;
	                    continue;
	                }
	                var name = hop.AMOUNT*1000 + 'g de ' + hop.NAME + ' (' + hop.USE + ' '+hop.TIME+'\')';
	                addPending(prevDelay - hopTime,name,'BOIL_HOP',hop._id.toString());
					prevDelay = hopTime;
				}
            }

			//add coling time for last hopping addiction
			coolingFixed[0].delay = prevDelay;
            addFixed(coolingFixed);

            //Hasta la inoculacion tomo el tiempo fijo de enfriado.
            prevDelay = COOLING_TIME;
            for( var i=0; i<$scope.recipe.fermentation.stages.length; i++ ) {
                var stage = $scope.recipe.fermentation.stages[i];

                var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == 'FERM_STAGE' && item.logRef == stage._id.toString() ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    prevDelay = convert2Minutes(stage);
                    continue;
                }

                var name =  stage.title+' - '+stage.duration+' '+stage.durationMode;
                name += ' - '+stage.temperature+'º';
                if ( stage.temperature != stage.temperatureEnd) {
                	name += ' a '+stage.temperatureEnd+'º';
                }

                addPending(prevDelay,name,'FERM_STAGE',stage._id.toString());
                prevDelay = convert2Minutes(stage);
            }

			//Hoping (only Dry-Hop)
            for( var i=0; i<$scope.recipe.HOPS.HOP.length; i++ ) {
                var hop = $scope.recipe.HOPS.HOP[i];
				if ( hop.USE === 'Dry Hop') {
					var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
	                    return item.logType == 'BOIL_HOP' && item.logRef == hop._id.toString() ? 0 : -1;
	                });
	                if ( filter.length != 0 ) {
	                    prevDelay = hop.TIME;
	                    continue;
	                }
	                var name = hop.AMOUNT*1000 + 'g de ' + hop.NAME + ' (' + hop.USE + ' '+hop.TIME+'\')';
	                addPending(prevDelay - hop.TIME,name,'BOIL_HOP',hop._id.toString());
	                prevDelay = hop.TIME;
				}
            }

            //en prevDelay me queda ya cargado el timpo del ultimo paso de fermentacion.
            //Embotellado
            for( var i=0; i<$scope.recipe.bottling.bottles.length; i++ ) {
            	var bottle = $scope.recipe.bottling.bottles[i];

				var filter = util.Arrays.filter($scope.recipe.log.logs,function(item) {
                    return item.logType == 'BOTTLING' && item.logRef == bottle._id.toString() ? 0 : -1;
                });
                if ( filter.length != 0 ) {
                    prevDelay = 0;
                    continue;
                }
                var name =  bottle.bottleType+' - '+bottle.amount+' Unidades';

                addPending(prevDelay,name,'BOTTLING',bottle._id.toString());
                prevDelay = 0;
            }

        };

        function convert2Minutes(stage) {
            if ( stage.durationMode =='Horas') {
                return stage.duration * 60;
            } else if ( stage.durationMode =='Dias') {
                return stage.duration * 60 * 24;
            }
        }

        function addPending(delay,detail,type,ref) {
            $scope.pendingLogs.push({
                prev: prevTime(),
                time: function() {
                    return addMinutes(this.prev,this.delay);
                },
                delay: delay,
                detail: detail,
                logType: type,
                logRef: ref
            });
        }

        $scope.calculatePending();

        function updatePendingTime() {
            if ( $scope.pendingLogs != 0 ) {
                $scope.pendingLogs[0].prev = $scope.now();
                for (var i=1; i<$scope.pendingLogs.length; i++) {
                    $scope.pendingLogs[i].prev = $scope.pendingLogs[i-1].time();
                }
            }
        }

        $scope.$watch("edit.time", function(value) {
            updatePendingTime();
        });

        $scope.pushAndEdit = function(log) {
        	$scope.push(log);
        	var last = $scope.recipe.log.logs[$scope.recipe.log.logs.length-1];
        	$scope.goEdit(last);
        };

        $scope.push = function(log) {
            log.time = new Date();
            $scope.recipe.log.logs.push({
                time: new Date(),
                delay: log.delay,
                detail: log.detail,
                logType: log.logType,
                logRef: log.logRef,
                discard: false
            });
            util.Arrays.remove($scope.pendingLogs,log);
            updatePendingTime();
        };

        $scope.discard = function(log) {
        	log.discard = true;
        };

        $scope.pushAndDiscard = function(log) {
        	$scope.push(log);
        	var last = $scope.recipe.log.logs[$scope.recipe.log.logs.length-1];
        	$scope.discard(last);
        };

		$scope.restoreAll = function() {
			$scope.recipe.log.logs = [];
			$scope.calculatePending();
		};

        /*
         * Remove Log from top, and put in down list again.
         */
        $scope.restore = function(log) {
        	util.Arrays.remove($scope.recipe.log.logs,log);
        	$scope.calculatePending();
        };
    });
})();
<|endoftext|>


<commit_before>app.factory('Minions', function($q) {
    var Minions = {};

    var TYPE_ID = {
        FEDERATION_NAVY_STASIS_WEBIFIER : 17559
    }

    var DD  = {
        VINDICATOR : 17740 ,
        ROKH : 24688 ,
        NIGHTMARE : 17736 ,
        MAELSTROM : 24694 ,
        HYPERION : 24690 ,
        MACHARIEL : 17738
    }

    var LL  = {
        SCIMITAR : 11978 ,
        BASILISK : 11985
    }

    function parseSlot(str){
        var arr = str.split(';');
        return {id: arr[0],n:arr[1]};
    }

    Minions.teardownShipFit = function(shipDNA){
        var slots = shipDNA.split(':')

        var type = slots.shift();
        var modules = slots.map(parseSlot);

        var ship = {type : type, modules : modules};
        return ship;
    }

    Minions.linkCharacter = function(id,name){
        return '<url=showinfo:1373\/\/' + id + '>' + name +'</url>'
    }

    Minions.linkFit = function(shipDNA,shipName){
        return '<url=fitting:' + shipDNA + '>' + shipName + '</url>'
    }

    Minions.waitlist2ascii = function(waitlist,head,foot){
        var list = waitlist.waitlist.map(function (item) {
            var char = item.characterName   // linkCharacter(item.characterId,item.characterName);
            var fit  = item.shipName        //linkFit(item.shipDNA,item.shipName)
            return ' * ' + fit + ' \t ' + char + '\n';
        })
        list = list.join('');

        var ascii = '.\n';
        var prename = waitlist.ownerName.split(' ')[0];
        head = head.replace('%n',prename)
        ascii = ascii.concat(head);
        ascii = ascii.concat(list);
        ascii = ascii.concat(foot)
        return ascii;
    }

    return Minions;
});<commit_msg>fixed ascii head newline<commit_after>app.factory('Minions', function($q) {
    var Minions = {};

    var TYPE_ID = {
        FEDERATION_NAVY_STASIS_WEBIFIER : 17559
    }

    var DD  = {
        VINDICATOR : 17740 ,
        ROKH : 24688 ,
        NIGHTMARE : 17736 ,
        MAELSTROM : 24694 ,
        HYPERION : 24690 ,
        MACHARIEL : 17738
    }

    var LL  = {
        SCIMITAR : 11978 ,
        BASILISK : 11985
    }

    function parseSlot(str){
        var arr = str.split(';');
        return {id: arr[0],n:arr[1]};
    }

    Minions.teardownShipFit = function(shipDNA){
        var slots = shipDNA.split(':')

        var type = slots.shift();
        var modules = slots.map(parseSlot);

        var ship = {type : type, modules : modules};
        return ship;
    }

    Minions.linkCharacter = function(id,name){
        return '<url=showinfo:1373\/\/' + id + '>' + name +'</url>'
    }

    Minions.linkFit = function(shipDNA,shipName){
        return '<url=fitting:' + shipDNA + '>' + shipName + '</url>'
    }

    Minions.waitlist2ascii = function(waitlist,head,foot){
        var list = waitlist.waitlist.map(function (item) {
            var char = item.characterName   // linkCharacter(item.characterId,item.characterName);
            var fit  = item.shipName        //linkFit(item.shipDNA,item.shipName)
            return ' * ' + fit + ' \t ' + char + '\n';
        })
        list = list.join('');

        var ascii = '.\n';
        var prename = waitlist.ownerName.split(' ')[0];
        head = head.replace('%n',prename)
        ascii = ascii.concat(head);
        ascii = ascii.concat('\n');
        ascii = ascii.concat(list);
        ascii = ascii.concat(foot)
        return ascii;
    }

    return Minions;
});<|endoftext|>


<commit_before>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	console.log("javascript for recordactivity.js connected!");
	$.get("/getdata", printData);
	console.log("YOOHOO");
	$(".submitBtn").click(submitClicked);
})

function printData(activities){
	for (var index in activities){
  		var activity = activities[index];
  		var activitydiv = $("#"+activity['activity']);
  		$(activitydiv).find("#progress_bar").css('width', (activity['hours']/activity['goal']*100)+'%');
  	}
}

function submitClicked(e){
	e.preventDefault();

	var activitydiv = $(this).closest(".activity");
	var activity = $(activitydiv).attr('id');
	var timeinput = $(activitydiv).find("#time");
	var time = timeinput.val();
	var hoursspent = $(activitydiv).find("#hoursspent").val();

	if(!validInput(time)){
		$('#message').removeClass();
		$('#message').addClass("alert alert-warning");
		$('#message').html("Please enter the hours spent doing this activity.");
		timeinput.val("");
		return;
	}

	if($(this).attr("id") == 'minusBtn'){
		time = -1 * time;
	}

	if(!withinRange(time, hoursspent)){
		$('#message').removeClass();
		$('#message').addClass("alert alert-warning");
		$('#message').html("You can only spend between 0 and 24 hours per day on each activity. Please enter another number.");
		timeinput.val("");
		return;
	}

	console.log(time);
	console.log(activity);

	var parameters = {'activity': activity, 'time': time };
	$.get("/addtime", parameters);
	$.get("/gettime", parameters, success)
}

function success(results){
	console.log(results);
	var message = results['message'];
	$('#message').removeClass();
	$('#message').addClass("alert alert-success");
	$('#message').html(message);

	var activitydiv = $("#"+results['activity']);
	console.log(activitydiv);
	$(activitydiv).find("#timespent").text(results['hours'] +" / "+ results['goal'] + " hrs");
	$(activitydiv).find("#progress_bar").css('width', (results['hours']/results['goal']*100)+'%');
}

function validInput(time){
	if(time == "")
		return false;
	var regexp = /^[0-9]*(.)[0-9]*$/;
    return (time.search(regexp) >= 0) ? true : false;
}

function withinRange(time, hoursspent){
	console.log ("hours spent: " + hoursspent);
	var total = parseInt(time) + parseInt(hoursspent);

	console.log("total" + total);
	console.log(parseInt(time) > 24);
	console.log(total < 0);
	if(total > 24 || total < 0)
		return false;
	else
		return true;
}
<commit_msg>Hitting enter adds the time on the homepage now! But there is a big where adding time doesn't seem to work with indexB....<commit_after>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	console.log("javascript for recordactivity.js connected!");
	$.get("/getdata", printData);
	console.log("YOOHOO");
	$(".submitBtn").click(submitClicked);
	$("#time").keydown(keyClicked);
})

function printData(activities){
	for (var index in activities){
  		var activity = activities[index];
  		var activitydiv = $("#"+activity['activity']);
  		$(activitydiv).find("#progress_bar").css('width', (activity['hours']/activity['goal']*100)+'%');
  	}
}

function keyClicked(e) {
	console.log("Got into the keyClicked");
	var keycode = (event.keyCode ? event.keyCode : event.which);
	if(keycode == '13'){
		e.preventDefault();
		console.log('You pressed a "enter" key in textbox');		var activitydiv = $(this).closest(".activity");
	var activity = $(activitydiv).attr('id');
	var timeinput = $(activitydiv).find("#time");
	var time = timeinput.val();
	var hoursspent = $(activitydiv).find("#hoursspent").val();

	if(!validInput(time)){
		$('#message').removeClass();
		$('#message').addClass("alert alert-warning");
		$('#message').html("Please enter the hours spent doing this activity.");
		timeinput.val("");
		return;
	}

	if(!withinRange(time, hoursspent)){
		$('#message').removeClass();
		$('#message').addClass("alert alert-warning");
		$('#message').html("You can only spend between 0 and 24 hours per day on each activity. Please enter another number.");
		timeinput.val("");
		return;
	}

	console.log(time);
	console.log(activity);

	var parameters = {'activity': activity, 'time': time };
	$.get("/addtime", parameters);
	$.get("/gettime", parameters, success)
	}

}

function submitClicked(e){
	e.preventDefault();

	var activitydiv = $(this).closest(".activity");
	var activity = $(activitydiv).attr('id');
	var timeinput = $(activitydiv).find("#time");
	var time = timeinput.val();
	var hoursspent = $(activitydiv).find("#hoursspent").val();

	if(!validInput(time)){
		$('#message').removeClass();
		$('#message').addClass("alert alert-warning");
		$('#message').html("Please enter the hours spent doing this activity.");
		timeinput.val("");
		return;
	}

	if($(this).attr("id") == 'minusBtn'){
		time = -1 * time;
	}

	if(!withinRange(time, hoursspent)){
		$('#message').removeClass();
		$('#message').addClass("alert alert-warning");
		$('#message').html("You can only spend between 0 and 24 hours per day on each activity. Please enter another number.");
		timeinput.val("");
		return;
	}

	console.log(time);
	console.log(activity);

	var parameters = {'activity': activity, 'time': time };
	$.get("/addtime", parameters);
	$.get("/gettime", parameters, success)
}

function success(results){
	console.log(results);
	var message = results['message'];
	$('#message').removeClass();
	$('#message').addClass("alert alert-success");
	$('#message').html(message);

	var activitydiv = $("#"+results['activity']);
	console.log(activitydiv);
	$(activitydiv).find("#timespent").text(results['hours'] +" / "+ results['goal'] + " hrs");
	$(activitydiv).find("#progress_bar").css('width', (results['hours']/results['goal']*100)+'%');
}

function validInput(time){
	if(time == "")
		return false;
	var regexp = /^[0-9]*(.)[0-9]*$/;
    return (time.search(regexp) >= 0) ? true : false;
}

function withinRange(time, hoursspent){
	console.log ("hours spent: " + hoursspent);
	var total = parseInt(time) + parseInt(hoursspent);

	console.log("total" + total);
	console.log(parseInt(time) > 24);
	console.log(total < 0);
	if(total > 24 || total < 0)
		return false;
	else
		return true;
}
<|endoftext|>


<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2012 Zynga Inc.
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

(function(undef)
{
	/** {=Map} Map of selected field values */
	var permutated = {};

	/** {=Map} Internal database of available fields with their current values */
	var selected = {};

	/** {=String} Computed checksum */
	var checksum = null;

	// At this level Array.prototype.indexOf might not be support, so we implement a custom logic for a contains check
	var contains = function(array, value)
	{
		for (var i=0, l=array.length; i<l; i++)
		{
			if (array[i] == value) {
				return true;
			}
		}
	};

	/**
	 * {var} Returns the value of the field with the given @name {String}.
	 */
	var getValue = function(name)
	{
		if (!(name in selected)) {
			throw new Error("[jasy.Env]: Field " + name + " is not available (yet)!");
		}

		return selected[name];
	};

	/**
	 * This class is the client-side representation for the permutation features of
	 * Jasy and supports features like auto-selecting builds based on specific feature sets.
	 */
	core.Module("jasy.Env",
	{
		/** {=Map} Map of all fields with their values. */
		SELECTED : selected,

		/** {=Map} Map of all permutated fields which are relevant for checksum compution */
		PERMUTATED : permutated,

		/**
		 * Configure environment data dynamically via setting a field @name {String} and its @value {var}.
		 */
		define : function(name, value) {
			selected[name] = value;
		},

		/**
		 * Adds the given @field {Array} as exported by Jasy.
		 */
		addField : function(field)
		{
			// possible variants
			// 1: name, 1, test, [val1, val2]
			// 2: name, 2, value
			// 3: name, 3, test, default (not permutated)

			var name = field[0];
			var type = field[1];
			if (type == 1 || type == 3)
			{
				var test = field[2];
				var value = "VALUE" in test ? test.VALUE : test.get(name);
				var third = field[3];

				// Fallback to first value if test results in unsupported value
				if (type == 1 && !contains(third, value)) {
					value = third[0];
				}

				// Fill in missing value with default
				else if (type == 3 && value == null) {
					value = third;
				}
			}
			else
			{
				// In cases with no test, we don't have an array of fields but just a value
				value = field[2];
			}

			// Add all fields - even static ones - to the selected data
			selected[name] = value;

			// Only add permutated fields to the permutated map.
			if (type != 3)
			{
				permutated[name] = value;
				checksum = null;
			}
		},

		/**
		 * {String} Returns the SHA1 checksum of the current permutated field set.
		 * This checksum computition is compatatible with the Jasy approach for
		 * computing it.
		 */
		getChecksum : function()
		{
			if (checksum != null) {
				return checksum;
			}

			var names = [];
			for (var name in permutated) {
				names.push(name);
			}

			names.sort();

			var list = [];
			for (var i=0, l=names.length; i<l; i++)
			{
				var name = names[i];
				list.push(name + ":" + permutated[name]);
			}

			var sha1 = core.crypt.SHA1.checksum(list.join(";"));
			return checksum = core.String.toHex(sha1);
		},

		/**
		 * Used by Jasy to inject @fields {Array} data
		 *
		 * Deprecated!
		 */
		setFields : function(fields)
		{
			for (var i=0, l=fields.length; i<l; i++) {
				this.addField(fields[i]);
			}
		},

		getValue : getValue,

		/**
		 * {Boolean} Whether the field with the given @name {String} was set to the given @value {var?true}.
		 *
		 * Boolean fields could also be checked without a given value as the value
		 * defaults to `true`.
		 */
		isSet : function(name, value)
		{
			// Fallback to value of true
			if (value === undef) {
				value = true;
			}

			// Explicit use of normal equal here to not differ between numbers and strings etc.
			return getValue(name) == value;
		},

		/**
		 * {var} Selects and returns the current value of the field with the given
		 * @name {String} from the given @map {Map}.
		 */
		select: function(name, map) {
			return map[getValue(name)];
		}
	});
})();

<commit_msg>Added new field type which is used to inject static - non permutation relevant data. Played with base62 encoding.<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2012 Zynga Inc.
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

(function(undef)
{
	/** {=Map} Map of selected field values */
	var permutated = {};

	/** {=Map} Internal database of available fields with their current values */
	var selected = {};

	/** {=String} Computed checksum */
	var checksum = null;

	// At this level Array.prototype.indexOf might not be support, so we implement a custom logic for a contains check
	var contains = function(array, value)
	{
		for (var i=0, l=array.length; i<l; i++)
		{
			if (array[i] == value) {
				return true;
			}
		}
	};

	/**
	 * {var} Returns the value of the field with the given @name {String}.
	 */
	var getValue = function(name)
	{
		if (!(name in selected)) {
			throw new Error("[jasy.Env]: Field " + name + " is not available (yet)!");
		}

		return selected[name];
	};

	/**
	 * This class is the client-side representation for the permutation features of
	 * Jasy and supports features like auto-selecting builds based on specific feature sets.
	 */
	core.Module("jasy.Env",
	{
		/** {=Map} Map of all fields with their values. */
		SELECTED : selected,

		/** {=Map} Map of all permutated fields which are relevant for checksum compution */
		PERMUTATED : permutated,

		/**
		 * Configure environment data dynamically via setting a field @name {String} and its @value {var}.
		 */
		define : function(name, value) {
			selected[name] = value;
		},

		/**
		 * Adds the given @field {Array} as exported by Jasy.
		 */
		addField : function(field)
		{
			// possible variants
			// 1: name, 1, test, [val1, val2]
			// 2: name, 2, value
			// 3: name, 3, test, default (not permutated)
			// 4: name, 4, value (not permutated)

			var name = field[0];
			var type = field[1];
			if (type == 1 || type == 3)
			{
				var test = field[2];
				var value = "VALUE" in test ? test.VALUE : test.get(name);
				var third = field[3];

				// Fallback to first value if test results in unsupported value
				if (type == 1 && !contains(third, value)) {
					value = third[0];
				}

				// Fill in missing value with default
				else if (type == 3 && value == null) {
					value = third;
				}
			}
			else
			{
				// In cases with no test, we don't have an array of fields but just a value
				value = field[2];
			}

			// Add all fields - even static ones - to the selected data
			selected[name] = value;

			// Only add permutated fields to the permutated map.
			if (type == 1 || type == 2)
			{
				permutated[name] = value;
				checksum = null;
			}
		},

		/**
		 * {String} Returns the SHA1 checksum of the current permutated field set.
		 * This checksum computition is compatatible with the Jasy approach for
		 * computing it.
		 */
		getChecksum : function()
		{
			if (checksum != null) {
				return checksum;
			}

			var names = [];
			for (var name in permutated) {
				names.push(name);
			}

			names.sort();

			var list = [];
			for (var i=0, l=names.length; i<l; i++)
			{
				var name = names[i];
				list.push(name + ":" + permutated[name]);
			}

			var sha1 = core.crypt.SHA1.checksum(list.join(";"));
			checksum = core.String.toHex(sha1);

			// var chk2 = core.util.Base62.encode(sha1);
			// console.log("COMPARE: ", checksum, chk2);
			return checksum;
		},

		/**
		 * Used by Jasy to inject @fields {Array} data
		 *
		 * Deprecated!
		 */
		setFields : function(fields)
		{
			for (var i=0, l=fields.length; i<l; i++) {
				this.addField(fields[i]);
			}
		},

		getValue : getValue,

		/**
		 * {Boolean} Whether the field with the given @name {String} was set to the given @value {var?true}.
		 *
		 * Boolean fields could also be checked without a given value as the value
		 * defaults to `true`.
		 */
		isSet : function(name, value)
		{
			// Fallback to value of true
			if (value === undef) {
				value = true;
			}

			// Explicit use of normal equal here to not differ between numbers and strings etc.
			return getValue(name) == value;
		},

		/**
		 * {var} Selects and returns the current value of the field with the given
		 * @name {String} from the given @map {Map}.
		 */
		select: function(name, map) {
			return map[getValue(name)];
		}
	});
})();

<|endoftext|>


<commit_before>'use strict';

/*
  query-runner.js

  This is where we query the database for the actual resource(s) and apply any
  default constraints that we might need to.
*/

module.exports = {

  inject: [ 'DS' ],

  middleware: function(DS) {

    return function(req, res, next) {
      var Model = DS[req.controller.model];
      req.rawResources = {};

      if (req.params.id) {
        var q = Model.findById(req.params.id).lean();

        q.exec(function(err, result) {
          if (err) return next(err);

          req.rawResources = result;
          return next();
        });
      } else if (!req.params.id && req.method === 'GET') {
        var q = Model.find(req.searchParams);
        var count = Model.count(req.searchParams);

        if (req.query.page) {
          var perPage = parseInt(req.query.perPage) || 20;
          q.skip((parseInt(req.query.page) * perPage) - perPage);
          q.limit(perPage);
        } else {
          q.limit(req.query.limit || 20);
        }

        q.lean().exec(function(err, result) {
          if (err) return next(err);

          count.lean().exec(function(err, counter) {
            if (err) return next(err);

            req.rawResources = result;
            req.rawResourcesCount = counter;
            return next();
          });
        });
      } else {
        return next();
      }
    }

  }

};
<commit_msg>refactoring query runner to reduce the pain<commit_after>'use strict';

/*
  query-runner.js

  This is where we query the database for the actual resource(s) and apply any
  default constraints that we might need to.
*/

module.exports = {

  inject: [ 'DS' ],

  middleware: function(DS) {

    return function(req, res, next) {
      var Model = DS[req.controller.model];
      req.rawResources = {};

      var query = false;
      var count = false;

      if (req.params.id) {
        query = Model.findById(req.params.id).lean();
      } else if (!req.params.id && req.method === 'GET') {
        query = Model.find(req.searchParams);
        count = Model.count(req.searchParams);

        if (req.query.page) {
          var perPage = parseInt(req.query.perPage) || 20;

          query = query.skip((parseInt(req.query.page) * perPage) - perPage);
          query = query.limit(perPage);
        } else {
          query = query.limit(req.query.limit || 20);
        }

        query = query.lean();
      } else {
        return next();
      }

      query.exec(function(err, result) {
        if (err) return next(err);

        req.rawResources = result;

        if (!count) return next();

        count.exec(function(err, counter) {
          if (err) return next(err);

          req.rawResourcesCount = counter;
          return next();
        });
      });
    }

  }

};
<|endoftext|>


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

 'use strict';

 const log = require('../net2/logger.js')(__filename);
 const util = require('util');
 const DataMigrator = require('./DataMigrator.js');
 let instance = null;

 const bclient = require('../util/redis_manager.js').getBufferRedisClient();
 const readline = require('readline');

 const partitionKeyMap = {
  "devices": [
    "host:*"
  ],
  "alarms": [
    "alarm:id",
    "_alarm:*",
    "_alarmDetail:*",
    "alarm_active",
    "alarm_archive"
  ],
  "rules": [
    "policy:id",
    "policy_active",
    "policy:*"
  ],
  "exceptions": [
    "exception:id",
    "exception:*",
    "exception_queue"
  ],
  "config": [
    "policy:system",
    "policy:mac:*",
    "ext.*",
    "scisurf.config",
    "sys:features",
    "mode"
  ],
  "intel": [
    "category:*",
    "dynamicCategoryDomain:*",
    "intel:*",
    "lastCategory:*",
    "cache.intel:*",
    "rdns:*",
    "dns:*",
    "srdns:*",
    "ip_set_to_be_processed",
    "software:ip:*",
    "user_agent:*",
    "app:*",
    "lastapp:*",
    "dhcp:*"
  ],
  "traffic": [
    "flow:*",
    "aggrflow:*",
    "appflow:*",
    "sumflow:*",
    "syssumflow:*",
    "lastsumflow:*",
    "categoryflow:*",
    "timedTraffic:*"
  ],
  "stats": [
    "boneAPIUsage:*",
    "neighbor:*",
    "stats:*"
  ],
  "mq": [
    "bq:*"
  ],
  "misc": [
    "monitored_hosts*",
    "unmonitored_hosts*",
    "zoffline_hosts"
  ]
};

class RedisMigrator extends DataMigrator {
  constructor() {
    super();
    if (instance == null) {
      instance = this;
    }
    return instance;
  }

  async _serializeRedisKey(key) {
    let result = "";
    const keyDump = await bclient.dumpAsync(key);
    if (keyDump !== null) {
      const ttl = await bclient.pttlAsync(key); // in milliseconds
      const record = {
        key: key.toString(),
        ttl: ttl,
        value: keyDump
      };
      result = JSON.stringify(record) + "\n";
    }
    return result;
  }

  async _deserializeRedisKey(record) {
    if (record !== "") {
      const recordJson = JSON.parse(record);
      const key = recordJson.key;
      const ttl = Math.max(0, recordJson.ttl);
      const value = Buffer.from(recordJson.value.data);
      await bclient.restoreAsync(key, ttl, value, "REPLACE");
    }
  }

  async export(partition, outputStream) {
    const keyPatterns = partitionKeyMap[partition];
    if (keyPatterns !== null) {
      for (let i in keyPatterns) {
        const pattern = keyPatterns[i];
        const keys = await bclient.keysAsync(pattern);
        log.info("Pattern: " + pattern + ", number of keys to dump: " + keys.length);
        while (keys.length > 0) {
          // concurrency limit
          const keysBatch = keys.splice(0, 4);
          await Promise.all(keysBatch.map(async key => {
            const serializedData = await this._serializeRedisKey(key);
            outputStream.write(Buffer.from(serializedData));
          }));
        }
        if (global.gc)
          global.gc();
      }
    }
    outputStream.end();
  }

  async import(inputStream) {
    const lineReader = readline.createInterface({
      input: inputStream
    });
    return new Promise((resolve, reject) => {
      lineReader.on('line', (line) => {
        this._deserializeRedisKey(line);
      });
      lineReader.on('close', () => {
        if (global.gc)
          global.gc();
        resolve();
      })
    })
  }
}

module.exports = RedisMigrator;<commit_msg>add ipmapping redis keys to intel partition in RedisMigrator.js<commit_after>/*    Copyright 2016 Firewalla LLC / Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 'use strict';

 const log = require('../net2/logger.js')(__filename);
 const util = require('util');
 const DataMigrator = require('./DataMigrator.js');
 let instance = null;

 const bclient = require('../util/redis_manager.js').getBufferRedisClient();
 const readline = require('readline');

 const partitionKeyMap = {
  "devices": [
    "host:*"
  ],
  "alarms": [
    "alarm:id",
    "_alarm:*",
    "_alarmDetail:*",
    "alarm_active",
    "alarm_archive"
  ],
  "rules": [
    "policy:id",
    "policy_active",
    "policy:*"
  ],
  "exceptions": [
    "exception:id",
    "exception:*",
    "exception_queue"
  ],
  "config": [
    "policy:system",
    "policy:mac:*",
    "ext.*",
    "scisurf.config",
    "sys:features",
    "mode"
  ],
  "intel": [
    "category:*",
    "dynamicCategoryDomain:*",
    "ipmapping:*",
    "intel:*",
    "lastCategory:*",
    "cache.intel:*",
    "rdns:*",
    "dns:*",
    "srdns:*",
    "ip_set_to_be_processed",
    "software:ip:*",
    "user_agent:*",
    "app:*",
    "lastapp:*",
    "dhcp:*"
  ],
  "traffic": [
    "flow:*",
    "aggrflow:*",
    "appflow:*",
    "sumflow:*",
    "syssumflow:*",
    "lastsumflow:*",
    "categoryflow:*",
    "timedTraffic:*"
  ],
  "stats": [
    "boneAPIUsage:*",
    "neighbor:*",
    "stats:*"
  ],
  "mq": [
    "bq:*"
  ],
  "misc": [
    "monitored_hosts*",
    "unmonitored_hosts*",
    "zoffline_hosts"
  ]
};

class RedisMigrator extends DataMigrator {
  constructor() {
    super();
    if (instance == null) {
      instance = this;
    }
    return instance;
  }

  async _serializeRedisKey(key) {
    let result = "";
    const keyDump = await bclient.dumpAsync(key);
    if (keyDump !== null) {
      const ttl = await bclient.pttlAsync(key); // in milliseconds
      const record = {
        key: key.toString(),
        ttl: ttl,
        value: keyDump
      };
      result = JSON.stringify(record) + "\n";
    }
    return result;
  }

  async _deserializeRedisKey(record) {
    if (record !== "") {
      const recordJson = JSON.parse(record);
      const key = recordJson.key;
      const ttl = Math.max(0, recordJson.ttl);
      const value = Buffer.from(recordJson.value.data);
      await bclient.restoreAsync(key, ttl, value, "REPLACE");
    }
  }

  async export(partition, outputStream) {
    const keyPatterns = partitionKeyMap[partition];
    if (keyPatterns !== null) {
      for (let i in keyPatterns) {
        const pattern = keyPatterns[i];
        const keys = await bclient.keysAsync(pattern);
        log.info("Pattern: " + pattern + ", number of keys to dump: " + keys.length);
        while (keys.length > 0) {
          // concurrency limit
          const keysBatch = keys.splice(0, 4);
          await Promise.all(keysBatch.map(async key => {
            const serializedData = await this._serializeRedisKey(key);
            outputStream.write(Buffer.from(serializedData));
          }));
        }
        if (global.gc)
          global.gc();
      }
    }
    outputStream.end();
  }

  async import(inputStream) {
    const lineReader = readline.createInterface({
      input: inputStream
    });
    return new Promise((resolve, reject) => {
      lineReader.on('line', (line) => {
        this._deserializeRedisKey(line);
      });
      lineReader.on('close', () => {
        if (global.gc)
          global.gc();
        resolve();
      })
    })
  }
}

module.exports = RedisMigrator;<|endoftext|>


<commit_before>'use strict';

var React = require('react');
var Reflux = require('reflux');
var _ = require('underscore');

var BasketItem = require('./BasketItem');
var {productsStore} = require('../Stores/productsStore');

var Basket = React.createClass({
    mixins: [
        Reflux.listenTo(productsStore, 'onProductsReceived')
    ],

    propTypes: {
        // there will be prop types
    },

    getInitialState(){
        return {
            basketItems: null
        }
    },

    onProductsReceived(data){
        console.log(data);
        var basketItems = data.filter(item => item.countInBasket > 0);
        this.setState({
            basketItems: basketItems
        })
    },

    getItemsCountInBasket(){
        return !_.isNull(this.state.basketItems) ?
            this.state.basketItems.reduce((sum, current) =>
                sum + current.countInBasket,0):
            null;
    },

    getTotalPrice(){
        return !_.isNull(this.state.basketItems) ?
            this.state.basketItems.reduce((sum, current) =>
                sum + (current.countInBasket * current.price),0):
            null;
    },

    getItems(){
        return !_.isNull(this.state.basketItems) ?
            this.state.basketItems.map(item =>
                <BasketItem item={_.clone(item)} key={item.id}/>
            ) :
            null;
    },

    render() {
        var basketCount = this.getItemsCountInBasket() || null;
        var totalPrice = this.getTotalPrice() ?

                $ {this.getTotalPrice().toFixed(2)}

 :
            null;
        return (

                    Shopping basket
                    {basketCount}

                    {this.getItems()}
                    {totalPrice}

        );
    }
});

module.exports = Basket;
<commit_msg>hide basket count block<commit_after>'use strict';

var React = require('react');
var Reflux = require('reflux');
var _ = require('underscore');

var BasketItem = require('./BasketItem');
var {productsStore} = require('../Stores/productsStore');

var Basket = React.createClass({
    mixins: [
        Reflux.listenTo(productsStore, 'onProductsReceived')
    ],

    propTypes: {
        // there will be prop types
    },

    getInitialState(){
        return {
            basketItems: null
        }
    },

    onProductsReceived(data){
        console.log(data);
        var basketItems = data.filter(item => item.countInBasket > 0);
        this.setState({
            basketItems: basketItems
        })
    },

    getItemsCountInBasket(){
        return !_.isNull(this.state.basketItems) ?
            this.state.basketItems.reduce((sum, current) =>
                sum + current.countInBasket,0):
            null;
    },

    getTotalPrice(){
        return !_.isNull(this.state.basketItems) ?
            this.state.basketItems.reduce((sum, current) =>
                sum + (current.countInBasket * current.price),0):
            null;
    },

    getItems(){
        return !_.isNull(this.state.basketItems) ?
            this.state.basketItems.map(item =>
                <BasketItem item={_.clone(item)} key={item.id}/>
            ) :
            null;
    },

    render() {
        var basketCount = this.getItemsCountInBasket() || null;
        var totalPrice = this.getTotalPrice() ?

                $ {this.getTotalPrice().toFixed(2)}

 :
            null;
        return (

                    Shopping basket
                    {basketCount}

                    {this.getItems()}
                    {totalPrice}

        );
    }
});

module.exports = Basket;
<|endoftext|>


<commit_before>function weightP(n){
  var rating = parseFloat($('#pRating' + n).val());
  var weight = parseFloat($('#pWheight' + n).val());

  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#pValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#pValue'+n).html(codigo);
    return weight/5*rating
  }

}

function tWeightP(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {
    total1 = total1 + parseFloat($('#pWheight' + i).val());
    total = total + weightP(i);
  }
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1+'
';
  }
  var codigo = '
'+total+'
';

  $("#tpWheight1").html(codigo1);
  $("#tpValue1").html(codigo);
}

function weightS(n){
  var rating = parseFloat($('#sRating' + n).val());
  var weight = parseFloat($('#sWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#sValue'+n).html(codigo);
    return 1
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#sValue'+n).html(codigo);
    return 2
    //weight/5*rating
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightS(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#sValue' + i).val());
    total = total + weightS(i);

  }
  var codigo = '
'+total+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1+'
';
  }

  $("#Tswheight").html(codigo1);
  $("#tsValue2").html(codigo);

}

function weightT(n){
  var rating = parseFloat($('#tRating' + n).val());
  var weight = parseFloat($('#tWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#tValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#tValue'+n).html(codigo);
    return weight/5*rating
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightT(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#tValue' + i).val());
    total = total + weightT(i);

  }
  var codigo = '
'+total+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1+'
';
  }

  $("#Ttwheight").html(codigo);
  $("#ttValue3").html(codigo1);
}

function showWeight(){

  tWeightP(4)

  for (var i = 1; i <= 10; i++) {
    weightS(i);
  }
  tWeightS(10)

  for (var i = 1; i <= 8; i++) {
    weightT(i);
  }
  tWeightT(8)
}
<commit_msg>sum fixes<commit_after>function weightP(n){
  var rating = parseFloat($('#pRating' + n).val());
  var weight = parseFloat($('#pWheight' + n).val());

  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#pValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#pValue'+n).html(codigo);
    return weight/5*rating
  }

}

function tWeightP(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {
    total1 = total1 + parseFloat($('#pWheight' + i).val());
    total = total + weightP(i);
  }
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1+'
';
  }
  var codigo = '
'+total+'
';

  $("#tpWheight1").html(codigo1);
  $("#tpValue1").html(codigo);
}

function weightS(n){
  var rating = parseFloat($('#sRating' + n).val());
  var weight = parseFloat($('#sWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#sValue'+n).html(codigo);
    return 1
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#sValue'+n).html(codigo);
    return 2
    //weight/5*rating
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightS(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#sValue' + i).val());
    total = total + weightS(i);

  }
  var codigo = '
'+total+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1+'
';
  }

  $("#Tswheight").html(codigo1);
  $("#tsValue2").html(codigo);

}

function weightT(n){
  var rating = parseFloat($('#tRating' + n).val());
  var weight = parseFloat($('#tWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#tValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#tValue'+n).html(codigo);
    return weight/5*rating
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightT(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#tValue' + i).val());
    total = total + weightT(i);

  }
  var codigo = '
'+total+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1+'
';
  }

  $("#Ttwheight").html(codigo);
  $("#ttValue3").html(codigo1);
}

function showWeight(){

  tWeightP(4)

  tWeightS(10)

  tWeightT(8)
}
<|endoftext|>


<commit_before>niclabs.insight.layer.MarkerLayer = (function($) {
    /**
     * Construct a new marker layer
     *
     * @class niclabs.insight.layer.MarkerLayer
     * @extends niclabs.insight.layer.Layer
     * @param {niclabs.insight.Dashboard} dashboard - dashboard that this layer belongs to
     * @param {Object} options - configuration options for the layer
     * @param {string} options.id - identifier for the layer
     * @param {string|Object[]} options.data - uri or data array for the layer
     */
    var MarkerLayer = function(dashboard, options) {
        var layer = niclabs.insight.Layer(dashboard, options);

        var attr = options.marker || {
            'type': 'simple-marker'
        };

        var markers = [];

        /**
         * Create marker from the type attribute
         *
         * @param {Object[]} data - layer data
         * @param {number} index - index of the marker in the data array
         * @param {Object} obj - configuration for the new marker
          */
        function newMarker(data, index, obj) {
            var marker;
            if ('type' in obj) {
                obj.layer = layer.id;
                obj.lat = data[index].lat;
                obj.lng = data[index].lng;

                marker = niclabs.insight.handler(obj.type)(dashboard, obj);
            }
            else {
                marker = obj;
            }

            return marker;
        }

        /**
         * Draw the markers according to the internal data on the map
         *
         * @memberof niclabs.insight.layer.MarkerLayer
         * @override
         * @param {Object[]} data - data to draw
         * @param {float} data[].lat - latitude for the marker
         * @param {float} data[].lng - longitude for the marker
         * @param {string=} data[].description - description for the marker
         */
        layer.draw = function(data) {
            for (var i = 0; i < data.length; i++) {
                markers.push(newMarker(data, i, attr));
            }
        };

        /**
         * Clear the markers from the map
         *
         * @memberof niclabs.insight.layer.MarkerLayer
         * @override
         */
        layer.clear = function() {
            for (var i = 0; i < markers.length; i++) {
                markers[i].clear();
            }
        };

        /**
         * Filter the layer according to the provided function.
         *
         * @memberof niclabs.insight.layer.MarkerLayer
         * @override
         * @param {niclabs.insight.layer.Layer~Filter} fn - filtering function
         */
        layer.filter = function(fn) {
            for (var i = 0; i < markers.length; i++) {
                markers[i].visible(fn(data[i]));
            }
        };

        return layer;
    };

    // Register the handler
    niclabs.insight.handler('marker-layer', 'layer', MarkerLayer);

    return MarkerLayer;
})(jQuery);
<commit_msg>[Fixed] correctly reference layer<commit_after>niclabs.insight.layer.MarkerLayer = (function($) {
    /**
     * Construct a new marker layer
     *
     * @class niclabs.insight.layer.MarkerLayer
     * @extends niclabs.insight.layer.Layer
     * @param {niclabs.insight.Dashboard} dashboard - dashboard that this layer belongs to
     * @param {Object} options - configuration options for the layer
     * @param {string} options.id - identifier for the layer
     * @param {string|Object[]} options.data - uri or data array for the layer
     */
    var MarkerLayer = function(dashboard, options) {
        var layer = niclabs.insight.layer.Layer(dashboard, options);

        var attr = options.marker || {
            'type': 'simple-marker'
        };

        var markers = [];

        /**
         * Create marker from the type attribute
         *
         * @param {Object[]} data - layer data
         * @param {number} index - index of the marker in the data array
         * @param {Object} obj - configuration for the new marker
          */
        function newMarker(data, index, obj) {
            var marker;
            if ('type' in obj) {
                obj.layer = layer.id;
                obj.lat = data[index].lat;
                obj.lng = data[index].lng;

                marker = niclabs.insight.handler(obj.type)(dashboard, obj);
            }
            else {
                marker = obj;
            }

            return marker;
        }

        /**
         * Draw the markers according to the internal data on the map
         *
         * @memberof niclabs.insight.layer.MarkerLayer
         * @override
         * @param {Object[]} data - data to draw
         * @param {float} data[].lat - latitude for the marker
         * @param {float} data[].lng - longitude for the marker
         * @param {string=} data[].description - description for the marker
         */
        layer.draw = function(data) {
            for (var i = 0; i < data.length; i++) {
                markers.push(newMarker(data, i, attr));
            }
        };

        /**
         * Clear the markers from the map
         *
         * @memberof niclabs.insight.layer.MarkerLayer
         * @override
         */
        layer.clear = function() {
            for (var i = 0; i < markers.length; i++) {
                markers[i].clear();
            }
        };

        /**
         * Filter the layer according to the provided function.
         *
         * @memberof niclabs.insight.layer.MarkerLayer
         * @override
         * @param {niclabs.insight.layer.Layer~Filter} fn - filtering function
         */
        layer.filter = function(fn) {
            for (var i = 0; i < markers.length; i++) {
                markers[i].visible(fn(data[i]));
            }
        };

        return layer;
    };

    // Register the handler
    niclabs.insight.handler('marker-layer', 'layer', MarkerLayer);

    return MarkerLayer;
})(jQuery);
<|endoftext|>


<commit_before>var fs = require('fs')                       // Node.js core
  , path = require('path');

var express = require('express')             // Express
  , app = express();

var bodyParser = require('body-parser')      // Express middleware
  , cookieParser = require('cookie-parser')
  , multer = require('multer')
  , session = require('express-session')
  , stylus = require('stylus')
  , flash = require('connect-flash')
  , morgan = require('morgan');

var mongoose = require('mongoose')           // Database
  , Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo; // Connect GFS and MongoDB

var uuid = require('node-uuid');             // Miscellaneous utilities
var yaml = require('js-yaml');

// Grab settings
var database = yaml.load(fs.readFileSync(__dirname + '/config/database.yaml', 'utf8'));
database.mongodb_uri = database.mongodb_uri || process.env['MONGODB_URI'];

// Include data models
fs.readdirSync(__dirname + '/app/models').forEach(function(file) {
  if (path.extname(file)) require(__dirname + '/app/models/' + file);
});

// Configure Express view engines and middleware
app.set('views', __dirname + '/app/views');
app.set('view engine', 'jade');
app.locals.pretty = true;

app.use(stylus.middleware(__dirname + '/public'));
app.use(express.static(__dirname + '/public'));
app.use(morgan('combined'));

// Setup view controller
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: uuid.v4(), saveUninitialized: true, resave: true}));
app.use(multer());
app.use(flash());

var Clock = require(__dirname + '/app/controllers/clock');
var Admin = require(__dirname + '/app/controllers/admin');
var Wallpaper = require(__dirname + '/app/controllers/wallpaper');

// We're ready!
console.log('Connecting to database...');
mongoose.connect(database.mongodb_uri);

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
  console.log('Connected!');

  app.use('/', Clock);
  app.use('/admin', Admin);
  app.use('/wallpaper', Wallpaper);

  // Setup 404
  app.use(function(req, res, next) {
    res.status(404);
    res.render('404');
  });

  var port = process.env.PORT || 3000;
  app.listen(port, function() {
    console.log('Listening on port ' + port);
  });
});
<commit_msg>Use localhost for MongoDB server if possible<commit_after>var fs = require('fs')                       // Node.js core
  , path = require('path');

var express = require('express')             // Express
  , app = express();

var bodyParser = require('body-parser')      // Express middleware
  , cookieParser = require('cookie-parser')
  , multer = require('multer')
  , session = require('express-session')
  , stylus = require('stylus')
  , flash = require('connect-flash')
  , morgan = require('morgan');

var mongoose = require('mongoose')           // Database
  , Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo; // Connect GFS and MongoDB

var uuid = require('node-uuid');             // Miscellaneous utilities
var yaml = require('js-yaml');

// Grab settings
var database = yaml.load(fs.readFileSync(__dirname + '/config/database.yaml', 'utf8'));
database.mongodb_uri = database.mongodb_uri || process.env['MONGODB_URI'] || 'localhost';

// Include data models
fs.readdirSync(__dirname + '/app/models').forEach(function(file) {
  if (path.extname(file)) require(__dirname + '/app/models/' + file);
});

// Configure Express view engines and middleware
app.set('views', __dirname + '/app/views');
app.set('view engine', 'jade');
app.locals.pretty = true;

app.use(stylus.middleware(__dirname + '/public'));
app.use(express.static(__dirname + '/public'));
app.use(morgan('combined'));

// Setup view controller
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret: uuid.v4(), saveUninitialized: true, resave: true}));
app.use(multer());
app.use(flash());

var Clock = require(__dirname + '/app/controllers/clock');
var Admin = require(__dirname + '/app/controllers/admin');
var Wallpaper = require(__dirname + '/app/controllers/wallpaper');

// We're ready!
console.log('Connecting to database...');
mongoose.connect(database.mongodb_uri);

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
  console.log('Connected!');

  app.use('/', Clock);
  app.use('/admin', Admin);
  app.use('/wallpaper', Wallpaper);

  // Setup 404
  app.use(function(req, res, next) {
    res.status(404);
    res.render('404');
  });

  var port = process.env.PORT || 3000;
  app.listen(port, function() {
    console.log('Listening on port ' + port);
  });
});
<|endoftext|>


<commit_before>$(document).ready(function(){

    $(window).on('load', function(){ updateView() });
    $(window).on('resize', function(){ updateView() });

    $('.btn.track').click( function () {
      var data = {
        "mode": $(this).attr('data-mode'),
        "type": "track",
        "track": [ $(this).attr('data-track') ],
        "id": null
      };
      $.post("load", data, function(data, status){
          //$.notify(data,"success");
          alert('success');
      });
    });

    $('div.frm input').focus(function(){
    	$(this).select();
	});

    //$("form#search input").val(decodeURIComponent(urlParam('q').replace(/\+/g, '%20')));

});

function updateView() {
	if ( $( window ).width() < 600 ) {
		$('body').addClass('mini');
	}
	else {
		$('body').removeClass('mini');
	}
}

function urlParam(name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results ? results[1] : '';
}
<commit_msg>Remove uneeded jQuery scripts<commit_after>$(document).ready(function(){
    $(window).on('load', function(){ updateView() });
    $(window).on('resize', function(){ updateView() });
    $('div.frm input').focus(function(){ $(this).select(); });
});

function updateView() {
	if ($( window ).width() < 600)
        $('body').addClass('mini');
	else
        $('body').removeClass('mini');
}
<|endoftext|>