<commit_before>// this function is also present in assignment-edit-views.js, we need to consolidate using moment.js

function formatDate(date) {
  if (date && !isNaN(date.getTime())) {
    return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
  } else return null;
}

function sortByOrder(a , b) {
  return a.get('order') - b.get('order');
}

FLOW.QuestionAnswerView = Ember.View.extend({

  isTextType: function(){
    return this.get('questionType') === 'FREE_TEXT';
  }.property('this.questionType'),

  isCascadeType: function(){
    return this.get('questionType') === 'CASCADE';
  }.property('this.questionType'),

  isOptionType: function(){
    return this.get('questionType') === 'OPTION';
  }.property('this.questionType'),

  isNumberType: function(){
    return this.get('questionType') === 'NUMBER';
  }.property('this.questionType'),

  isBarcodeType: function(){
    return this.get('questionType') === 'SCAN';
  }.property('this.questionType'),

  isDateType: function(){
    return this.get('questionType') === 'DATE';
  }.property('this.questionType'),

  isPhotoType: function(){
    return this.get('questionType') === 'PHOTO';
  }.property('this.questionType'),

  isVideoType: function(){
    return this.get('questionType') === 'VIDEO';
  }.property('this.questionType'),

  isGeoShapeType: function(){
    return this.get('questionType') === 'GEOSHAPE';
  }.property('this.questionType'),

  nonEditableQuestionTypes: ['GEO', 'PHOTO', 'VIDEO', 'GEOSHAPE'],

  form: function() {
    if (FLOW.selectedControl.get('selectedSurvey')) {
      return FLOW.selectedControl.get('selectedSurvey');
    }
  }.property('FLOW.selectedControl.selectedSurvey'),

  /*
   * Get the full list of options related to a particular option type question
   */
  optionsList: function(){
    var c = this.content;
    if (Ember.none(c) || !this.get('isOptionType')) {
      return Ember.A([]);
    }

    var questionId = c.get('questionID');

    var options = FLOW.store.filter(FLOW.QuestionOption, function (item) {
      return item.get('questionId') === +questionId;
    });

    optionArray = options.toArray();
    optionArray.sort(function (a, b) {
        return a.get('order') - b.get('order');
    });

    tempList = Ember.A([]);
    var obj;
    optionArray.forEach(function (item) {
      obj = Ember.Object.create({
        code : item.get('code'),
        text : item.get('text'),
        order: item.get('order')
      });
      tempList.push(obj);
    });

    // add other option if enabed
    var setOptionCodes = tempList.get('firstObject').get('code');
    if (this.get('isOtherOptionEnabled')) {
      tempList.push(Ember.Object.create({
        code: setOptionCodes ? "OTHER" : null, // OTHER is default code
        text: null,
        order: tempList.get('length'),
        isOther: true,
      }));
    }
    return tempList;
  }.property('this.content'),

  content: null,

  inEditMode: false,

  isNotEditable: function() {
    // keep this property to limit template rafactoring
    return !this.get('isEditable');
  }.property('this.isEditable'),

  isEditable: function () {
    var isEditableQuestionType, canEditFormResponses;
    isEditableQuestionType = this.nonEditableQuestionTypes.indexOf(this.get('questionType')) < 0;
    if (!isEditableQuestionType) {
      return false; // no need to check permissions
    }

    canEditFormResponses = FLOW.permControl.canEditResponses(this.get('form'));
    return isEditableQuestionType && canEditFormResponses;
  }.property('this.questionType,this.form'),

  date: null,

  numberValue: null,

  cascadeValue: function(key, value, previousValue){
    var c = this.content;
    // setter
    if (arguments.length > 1) {
      // split according to pipes
      var cascadeNames = value.split("|");
      var cascadeResponse = [];
      var obj = null;
      cascadeNames.forEach(function(item){
        if (item.trim().length > 0) {
          obj = {};
          obj.name = item.trim();
          cascadeResponse.push(obj);
        }
      });

      c.set('value', JSON.stringify(cascadeResponse));
    }

    // getter
    var cascadeString = "", cascadeJson;
    if (c && c.get('value')) {
      if (c.get('value').indexOf("|") > -1) {
        cascadeString += c.get('value');
      } else {
        cascadeJson = JSON.parse(c.get('value'));
        cascadeString = cascadeJson.map(function(item){
          return item.name;
        }).join("|");
      }
      return cascadeString;
    }
    return null;
  }.property('this.content'),

  /*
   *  A view property to set and retrieve the string response from the value property
   *  of an option question.
   *
   *  The setter block takes an Ember array consisting of selected elements from the
   *  optionsList and transforms this into a JSON formatted string stored in the response.
   *
   *  The getter block uses the string response to create an Ember array consisting
   *  of the corresponding elements from the optionsList property, i.e, selected elements
   *  of the optionsList.
   *
   *  Retrieved string responses could be:
   *   - pipe-separated strings for legacy format e.g. 'text1|text2'
   *   - JSON string in the current format e.g
   *    '[{text: "text with code", code: "code"}]'
   *    '[{text: "only text"}]'
   */
  optionValue: function (key, value, previousValue) {
    var valueArray = [], selectedOptions = Ember.A(), c = this.content, isOtherEnabled;

    // setter
    if (c && arguments.length > 1) {
      selectedOptions = value;
      selectedOptions.forEach(function (option) {
        var valueObj = {};
        valueObj.text = option.text;
        if (option.code) {
          valueObj.code = option.code;
        }
        valueArray.push(valueObj);
      });
      c.set('value', JSON.stringify(valueArray));
    }

    // getter
    var val, optionsList, textArray = [];
    if (c && c.get('value')) {
      val = c.get('value');
      optionsList = this.get('optionsList');
      isOtherEnabled = this.get('isOtherOptionEnabled');

      if (val.charAt(0) === '[') {
        // responses in JSON format
        JSON.parse(val).forEach(function (response) {
          optionsList.forEach(function (optionObj) {
            if (response.text === optionObj.get('text') &&
                response.code == optionObj.get('code')) { // '==' because codes could be undefined or null
              selectedOptions.addObject(optionObj);
            }

            // add other
            if (response.isOther && optionObj.get('isOther') && isOtherEnabled) {
              optionsList.get('lastObject').set('text', response.text);
              selectedOptions.addObject(optionsList.get('lastObject'));
            }
          });
        });
      } else {
        // responses in pipe separated format
        val.split("|").forEach(function(item){
          if (item.trim().length > 0) {
            textArray.push(item.trim());
          }
        });

        optionsList.forEach(function(optionObj, i) {
          if (textArray.indexOf(optionObj.get('text')) > -1) {
            selectedOptions.addObject(optionObj);
          }
        });
      }
      return selectedOptions.sort(sortByOrder);
    }
    return null;
  }.property('this.content'),

  /*
   *  A property to enable setting and getting of the selected element
   *  of a single-select option question.
   *
   */
  singleSelectOptionValue: function (key, value, previousValue) {
    var selectedOptions, c = this.content;

    // setter
    if (c && arguments.length > 1) {
      selectedOptions = Ember.A();
      selectedOptions.push(value);
      this.set('optionValue', selectedOptions);
    }

    // getter
    var options = this.get('optionValue');
    if (options && options.get('length') === 1) {
      return options.get('firstObject');
    }
    return null;
  }.property('this.optionValue'),

  /*
   *  A property to enable setting and getting of the selected element
   *  of a multi-select option question.
   *
   */
  multiSelectOptionValue: function (key, value, previousValue) {
    var c = this.content;

    // setter
    if (c && arguments.length > 1) {
      this.set('optionValue', value);
    }

    // getter
    return this.get('optionValue');
  }.property('this.optionValue'),

  isMultipleSelectOption: function () {
    return this.get('isOptionType') && this.get('question').get('allowMultipleFlag');
  }.property('this.isOptionType'),

  isOtherOptionEnabled: function () {
    return this.get('isOptionType') && this.get('question').get('allowOtherFlag');
  }.property('this.isOptionType'),

  photoUrl: function(){
    var c = this.content;
    if (!Ember.empty(c.get('value'))) {
      return FLOW.Env.photo_url_root + c.get('value').split('/').pop();
    }
  }.property('this.content,this.isPhotoType,this.isVideoType'),

  geoShapeObject: function(){
    var c = this.content;
    if (!Ember.empty(c.get('value'))) {
      return c.get('value');
    }
  }.property('this.content,this.isGeoShapeType'),

  questionType: function(){
    if(this.get('question')){
      return this.get('question').get('type');
    }
  }.property('this.question'),

  question: function(){
    var c = this.get('content');
    if (c) {
      var questionId = c.get('questionID');
      var q = FLOW.questionControl.findProperty('keyId', +questionId);
      return q;
    }
  }.property('this.content'),

  init: function () {
    this._super();
  },

  doEdit: function () {
    this.set('inEditMode', true);
    var c = this.content;

    if (this.get('isDateType') && !Ember.empty(c.get('value'))) {
      var d = new Date(+c.get('value')); // need to coerce c.get('value') due to milliseconds
      this.set('date', formatDate(d));
    }

    if (this.get('isNumberType') && !Ember.empty(c.get('value'))) {
      this.set('numberValue', c.get('value'));
    }
  },

  doCancel: function () {
    this.set('inEditMode', false);
  },

  doSave: function () {

    if (this.get('isDateType')) {
      var d = Date.parse(this.get('date'));
      if (isNaN(d) || d < 0) {
        this.content.set('value', null);
      } else {
        this.content.set('value', d);
      }
    }

    if (this.get('isNumberType')) {
      if (isNaN(this.numberValue)) {
        this.content.set('value', null);
      } else {
        this.content.set('value', this.numberValue);
      }
    }
    FLOW.store.commit();
    this.set('inEditMode', false);

  },

  doValidateNumber: function () {
    // TODO should check for minus sign and decimal point, depending on question setting
    this.set('numberValue', this.get('numberValue').toString().replace(/[^\d.]/g, ""));
  }.observes('this.numberValue')
});

FLOW.QuestionAnswerOptionListView = Ember.CollectionView.extend({
  tagName: 'ul',
  content: null,
  itemViewClass: Ember.View.extend({
    template: Ember.Handlebars.compile("{{view.content.text}}")
  })
});

/**
 * Multi select option editing view that renders question options with the allow
 * multiple option selected.  THe selection property should be a set of options
 * that are considered to be selected (checked).  Whenever each options checkbox
 * is modified, the set bound to the selection property is updated to add or remove
 * the item.
 */
FLOW.QuestionAnswerMultiOptionEditView = Ember.CollectionView.extend({
  tagName: 'ul',
  content: null,
  selection: null,
  itemViewClass: Ember.View.extend({
    template: Ember.Handlebars.compile("{{view Ember.Checkbox checkedBinding=\"view.isSelected\"}}{{view.content.text}}"),
    isSelected: function(key, checked, previousValue) {
      var selectedOptions = this.get('parentView').get('selection');
      var newSelectedOptions = Ember.A();

      // setter
      if (arguments.length > 1) {
        if (checked) {
          selectedOptions.addObject(this.content);
        } else {
          selectedOptions.removeObject(this.content);
        }
        selectedOptions.forEach(function(option){
          newSelectedOptions.push(option);
        });

        // Using a copy of the selected options 'newSelectedOptions' in order
        // to trigger the setter property of the object bound to 'parentView.selection'
        this.set('parentView.selection', newSelectedOptions);
      }

      // getter
      return selectedOptions && selectedOptions.contains(this.content);
    }.property('this.content'),
  })
});

FLOW.QuestionAnswerInspectDataView = FLOW.QuestionAnswerView.extend({
  templateName: 'navData/question-answer',
});
<commit_msg>[#828] Use local `optionObj` var to set selected option<commit_after>// this function is also present in assignment-edit-views.js, we need to consolidate using moment.js

function formatDate(date) {
  if (date && !isNaN(date.getTime())) {
    return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
  } else return null;
}

function sortByOrder(a , b) {
  return a.get('order') - b.get('order');
}

FLOW.QuestionAnswerView = Ember.View.extend({

  isTextType: function(){
    return this.get('questionType') === 'FREE_TEXT';
  }.property('this.questionType'),

  isCascadeType: function(){
    return this.get('questionType') === 'CASCADE';
  }.property('this.questionType'),

  isOptionType: function(){
    return this.get('questionType') === 'OPTION';
  }.property('this.questionType'),

  isNumberType: function(){
    return this.get('questionType') === 'NUMBER';
  }.property('this.questionType'),

  isBarcodeType: function(){
    return this.get('questionType') === 'SCAN';
  }.property('this.questionType'),

  isDateType: function(){
    return this.get('questionType') === 'DATE';
  }.property('this.questionType'),

  isPhotoType: function(){
    return this.get('questionType') === 'PHOTO';
  }.property('this.questionType'),

  isVideoType: function(){
    return this.get('questionType') === 'VIDEO';
  }.property('this.questionType'),

  isGeoShapeType: function(){
    return this.get('questionType') === 'GEOSHAPE';
  }.property('this.questionType'),

  nonEditableQuestionTypes: ['GEO', 'PHOTO', 'VIDEO', 'GEOSHAPE'],

  form: function() {
    if (FLOW.selectedControl.get('selectedSurvey')) {
      return FLOW.selectedControl.get('selectedSurvey');
    }
  }.property('FLOW.selectedControl.selectedSurvey'),

  /*
   * Get the full list of options related to a particular option type question
   */
  optionsList: function(){
    var c = this.content;
    if (Ember.none(c) || !this.get('isOptionType')) {
      return Ember.A([]);
    }

    var questionId = c.get('questionID');

    var options = FLOW.store.filter(FLOW.QuestionOption, function (item) {
      return item.get('questionId') === +questionId;
    });

    optionArray = options.toArray();
    optionArray.sort(function (a, b) {
        return a.get('order') - b.get('order');
    });

    tempList = Ember.A([]);
    var obj;
    optionArray.forEach(function (item) {
      obj = Ember.Object.create({
        code : item.get('code'),
        text : item.get('text'),
        order: item.get('order')
      });
      tempList.push(obj);
    });

    // add other option if enabed
    var setOptionCodes = tempList.get('firstObject').get('code');
    if (this.get('isOtherOptionEnabled')) {
      tempList.push(Ember.Object.create({
        code: setOptionCodes ? "OTHER" : null, // OTHER is default code
        text: null,
        order: tempList.get('length'),
        isOther: true,
      }));
    }
    return tempList;
  }.property('this.content'),

  content: null,

  inEditMode: false,

  isNotEditable: function() {
    // keep this property to limit template rafactoring
    return !this.get('isEditable');
  }.property('this.isEditable'),

  isEditable: function () {
    var isEditableQuestionType, canEditFormResponses;
    isEditableQuestionType = this.nonEditableQuestionTypes.indexOf(this.get('questionType')) < 0;
    if (!isEditableQuestionType) {
      return false; // no need to check permissions
    }

    canEditFormResponses = FLOW.permControl.canEditResponses(this.get('form'));
    return isEditableQuestionType && canEditFormResponses;
  }.property('this.questionType,this.form'),

  date: null,

  numberValue: null,

  cascadeValue: function(key, value, previousValue){
    var c = this.content;
    // setter
    if (arguments.length > 1) {
      // split according to pipes
      var cascadeNames = value.split("|");
      var cascadeResponse = [];
      var obj = null;
      cascadeNames.forEach(function(item){
        if (item.trim().length > 0) {
          obj = {};
          obj.name = item.trim();
          cascadeResponse.push(obj);
        }
      });

      c.set('value', JSON.stringify(cascadeResponse));
    }

    // getter
    var cascadeString = "", cascadeJson;
    if (c && c.get('value')) {
      if (c.get('value').indexOf("|") > -1) {
        cascadeString += c.get('value');
      } else {
        cascadeJson = JSON.parse(c.get('value'));
        cascadeString = cascadeJson.map(function(item){
          return item.name;
        }).join("|");
      }
      return cascadeString;
    }
    return null;
  }.property('this.content'),

  /*
   *  A view property to set and retrieve the string response from the value property
   *  of an option question.
   *
   *  The setter block takes an Ember array consisting of selected elements from the
   *  optionsList and transforms this into a JSON formatted string stored in the response.
   *
   *  The getter block uses the string response to create an Ember array consisting
   *  of the corresponding elements from the optionsList property, i.e, selected elements
   *  of the optionsList.
   *
   *  Retrieved string responses could be:
   *   - pipe-separated strings for legacy format e.g. 'text1|text2'
   *   - JSON string in the current format e.g
   *    '[{text: "text with code", code: "code"}]'
   *    '[{text: "only text"}]'
   */
  optionValue: function (key, value, previousValue) {
    var valueArray = [], selectedOptions = Ember.A(), c = this.content, isOtherEnabled;

    // setter
    if (c && arguments.length > 1) {
      selectedOptions = value;
      selectedOptions.forEach(function (option) {
        var valueObj = {};
        valueObj.text = option.text;
        if (option.code) {
          valueObj.code = option.code;
        }
        valueArray.push(valueObj);
      });
      c.set('value', JSON.stringify(valueArray));
    }

    // getter
    var val, optionsList, textArray = [];
    if (c && c.get('value')) {
      val = c.get('value');
      optionsList = this.get('optionsList');
      isOtherEnabled = this.get('isOtherOptionEnabled');

      if (val.charAt(0) === '[') {
        // responses in JSON format
        JSON.parse(val).forEach(function (response) {
          optionsList.forEach(function (optionObj) {
            if (response.text === optionObj.get('text') &&
                response.code == optionObj.get('code')) { // '==' because codes could be undefined or null
              selectedOptions.addObject(optionObj);
            }

            // add other
            if (response.isOther && optionObj.get('isOther') && isOtherEnabled) {
              optionObj.set('text', response.text);
              selectedOptions.addObject(optionObj);
            }
          });
        });
      } else {
        // responses in pipe separated format
        val.split("|").forEach(function(item){
          if (item.trim().length > 0) {
            textArray.push(item.trim());
          }
        });

        optionsList.forEach(function(optionObj, i) {
          if (textArray.indexOf(optionObj.get('text')) > -1) {
            selectedOptions.addObject(optionObj);
          }
        });
      }
      return selectedOptions.sort(sortByOrder);
    }
    return null;
  }.property('this.content'),

  /*
   *  A property to enable setting and getting of the selected element
   *  of a single-select option question.
   *
   */
  singleSelectOptionValue: function (key, value, previousValue) {
    var selectedOptions, c = this.content;

    // setter
    if (c && arguments.length > 1) {
      selectedOptions = Ember.A();
      selectedOptions.push(value);
      this.set('optionValue', selectedOptions);
    }

    // getter
    var options = this.get('optionValue');
    if (options && options.get('length') === 1) {
      return options.get('firstObject');
    }
    return null;
  }.property('this.optionValue'),

  /*
   *  A property to enable setting and getting of the selected element
   *  of a multi-select option question.
   *
   */
  multiSelectOptionValue: function (key, value, previousValue) {
    var c = this.content;

    // setter
    if (c && arguments.length > 1) {
      this.set('optionValue', value);
    }

    // getter
    return this.get('optionValue');
  }.property('this.optionValue'),

  isMultipleSelectOption: function () {
    return this.get('isOptionType') && this.get('question').get('allowMultipleFlag');
  }.property('this.isOptionType'),

  isOtherOptionEnabled: function () {
    return this.get('isOptionType') && this.get('question').get('allowOtherFlag');
  }.property('this.isOptionType'),

  photoUrl: function(){
    var c = this.content;
    if (!Ember.empty(c.get('value'))) {
      return FLOW.Env.photo_url_root + c.get('value').split('/').pop();
    }
  }.property('this.content,this.isPhotoType,this.isVideoType'),

  geoShapeObject: function(){
    var c = this.content;
    if (!Ember.empty(c.get('value'))) {
      return c.get('value');
    }
  }.property('this.content,this.isGeoShapeType'),

  questionType: function(){
    if(this.get('question')){
      return this.get('question').get('type');
    }
  }.property('this.question'),

  question: function(){
    var c = this.get('content');
    if (c) {
      var questionId = c.get('questionID');
      var q = FLOW.questionControl.findProperty('keyId', +questionId);
      return q;
    }
  }.property('this.content'),

  init: function () {
    this._super();
  },

  doEdit: function () {
    this.set('inEditMode', true);
    var c = this.content;

    if (this.get('isDateType') && !Ember.empty(c.get('value'))) {
      var d = new Date(+c.get('value')); // need to coerce c.get('value') due to milliseconds
      this.set('date', formatDate(d));
    }

    if (this.get('isNumberType') && !Ember.empty(c.get('value'))) {
      this.set('numberValue', c.get('value'));
    }
  },

  doCancel: function () {
    this.set('inEditMode', false);
  },

  doSave: function () {

    if (this.get('isDateType')) {
      var d = Date.parse(this.get('date'));
      if (isNaN(d) || d < 0) {
        this.content.set('value', null);
      } else {
        this.content.set('value', d);
      }
    }

    if (this.get('isNumberType')) {
      if (isNaN(this.numberValue)) {
        this.content.set('value', null);
      } else {
        this.content.set('value', this.numberValue);
      }
    }
    FLOW.store.commit();
    this.set('inEditMode', false);

  },

  doValidateNumber: function () {
    // TODO should check for minus sign and decimal point, depending on question setting
    this.set('numberValue', this.get('numberValue').toString().replace(/[^\d.]/g, ""));
  }.observes('this.numberValue')
});

FLOW.QuestionAnswerOptionListView = Ember.CollectionView.extend({
  tagName: 'ul',
  content: null,
  itemViewClass: Ember.View.extend({
    template: Ember.Handlebars.compile("{{view.content.text}}")
  })
});

/**
 * Multi select option editing view that renders question options with the allow
 * multiple option selected.  THe selection property should be a set of options
 * that are considered to be selected (checked).  Whenever each options checkbox
 * is modified, the set bound to the selection property is updated to add or remove
 * the item.
 */
FLOW.QuestionAnswerMultiOptionEditView = Ember.CollectionView.extend({
  tagName: 'ul',
  content: null,
  selection: null,
  itemViewClass: Ember.View.extend({
    template: Ember.Handlebars.compile("{{view Ember.Checkbox checkedBinding=\"view.isSelected\"}}{{view.content.text}}"),
    isSelected: function(key, checked, previousValue) {
      var selectedOptions = this.get('parentView').get('selection');
      var newSelectedOptions = Ember.A();

      // setter
      if (arguments.length > 1) {
        if (checked) {
          selectedOptions.addObject(this.content);
        } else {
          selectedOptions.removeObject(this.content);
        }
        selectedOptions.forEach(function(option){
          newSelectedOptions.push(option);
        });

        // Using a copy of the selected options 'newSelectedOptions' in order
        // to trigger the setter property of the object bound to 'parentView.selection'
        this.set('parentView.selection', newSelectedOptions);
      }

      // getter
      return selectedOptions && selectedOptions.contains(this.content);
    }.property('this.content'),
  })
});

FLOW.QuestionAnswerInspectDataView = FLOW.QuestionAnswerView.extend({
  templateName: 'navData/question-answer',
});
<|endoftext|>


<commit_before>$(document).ready(function() {
  $("div.elements-list")
  .on("click", "button.button-delete", function() {
    $(this).yesnoDialogRemote({
      topic: $.i18n._('confirmation_elective_block_delete')
    });
    $(this).yesnoDialogRemote("show");
  })
  .on("checkbox-change-state", "button.button-checkbox", function() {
    $(this).toggleClass('button-small-checkbox-selected');
    $(this).next().prop('disabled', !$(this).next().is(":disabled"));
  })
  .on("checkbox-uncheck", "button.button-checkbox", function() {
    $(this).removeClass('button-small-checkbox-selected');
    $(this).next().prop('disabled', true);
  })
  .on("click", "button.button-checkbox", function() {
    $(this).trigger("checkbox-change-state");
  })
  .on("click", "a.button-perform-scheduling", function() {
    if(!$(this).hasClass("disabled")) {
      $(this).yesnoDialogRemote({
        topic: $.i18n._('confirmation_elective_blocks_scheduler'),
        confirmation_action: function() {
          var that = this;
          this.footer.find("button.btn-confirmation").click(function() {
            var ctxt = $("form.elective-blocks-form");
            var form = $("<form method='post'/>");
            form.append($("<input name='_method' >").val(that.element.data("method")))
            .append(ctxt.find("input[name='authenticity_token']"));
            form.prop("action", that.element.prop('href'));
            $("body").append(form);
            form.submit();
          });
        }
      });
      $(this).yesnoDialogRemote("show");
    }
    return false;
  });

  $("button.destroy-all").lazy_form_confirmable_action({
    topic: 'confirmation_elective_blocks_delete',
    success_action: function(obj, key, val) {
      $("#elective-block-"+key).remove();
    }
  });
  $("button.select-all").click(function() {
    $("button.button-checkbox", "div.theses-list").trigger("checkbox-change-state");
  });
});<commit_msg>Fix: select-all button doesn't work<commit_after>$(document).ready(function() {
  $("div.elements-list")
  .on("click", "button.button-delete", function() {
    $(this).yesnoDialogRemote({
      topic: $.i18n._('confirmation_elective_block_delete')
    });
    $(this).yesnoDialogRemote("show");
  })
  .on("checkbox-change-state", "button.button-checkbox", function() {
    $(this).toggleClass('button-small-checkbox-selected');
    $(this).next().prop('disabled', !$(this).next().is(":disabled"));
  })
  .on("checkbox-uncheck", "button.button-checkbox", function() {
    $(this).removeClass('button-small-checkbox-selected');
    $(this).next().prop('disabled', true);
  })
  .on("click", "button.button-checkbox", function() {
    $(this).trigger("checkbox-change-state");
  })
  .on("click", "a.button-perform-scheduling", function() {
    if(!$(this).hasClass("disabled")) {
      $(this).yesnoDialogRemote({
        topic: $.i18n._('confirmation_elective_blocks_scheduler'),
        confirmation_action: function() {
          var that = this;
          this.footer.find("button.btn-confirmation").click(function() {
            var ctxt = $("form.elective-blocks-form");
            var form = $("<form method='post'/>");
            form.append($("<input name='_method' >").val(that.element.data("method")))
            .append(ctxt.find("input[name='authenticity_token']"));
            form.prop("action", that.element.prop('href'));
            $("body").append(form);
            form.submit();
          });
        }
      });
      $(this).yesnoDialogRemote("show");
    }
    return false;
  });

  $("button.destroy-all").lazy_form_confirmable_action({
    topic: 'confirmation_elective_blocks_delete',
    success_action: function(obj, key, val) {
      $("#elective-block-"+key).remove();
    }
  });
  $("button.select-all").click(function() {
    $("button.button-checkbox", "div.elective-blocks-list").trigger("checkbox-change-state");
  });
});<|endoftext|>


<commit_before>/**
 * @author troffmo5 / http://github.com/troffmo5
 *
 * Effect to render the scene in stereo 3d side by side with lens distortion.
 * It is written to be used with the Oculus Rift (http://www.oculusvr.com/) but
 * it works also with other HMD using the same technology
 */

THREE.OculusRiftEffect = function ( renderer, options ) {
	// worldFactor indicates how many units is 1 meter
	var worldFactor = (options && options.worldFactor) ? options.worldFactor: 1.0;

	// Specific HMD parameters
	var HMD = (options && options.HMD) ? options.HMD: {
		// Parameters from the Oculus Rift DK1
		hResolution: window.innerWidth,
		vResolution: window.innerHeight,
		hScreenSize: 0.14976,
		vScreenSize: 0.0936,
		interpupillaryDistance: 0.064,
		lensSeparationDistance: 0.064,
		eyeToScreenDistance: 0.041,
		distortionK : [1.0, 0.22, 0.24, 0.0],
		chromaAbParameter: [ 0.996, -0.004, 1.014, 0.0]
	};

	// Perspective camera
	var pCamera = new THREE.PerspectiveCamera();
	pCamera.matrixAutoUpdate = false;
	pCamera.target = new THREE.Vector3();

	// Orthographic camera
	var oCamera = new THREE.OrthographicCamera( -1, 1, 1, -1, 1, 1000 );
	oCamera.position.z = 1;

	// pre-render hooks
	this.preLeftRender = function() {};
	this.preRightRender = function() {};

  this.renderTarget = false;
  this.outputTarget = false;

	renderer.autoClear = false;
	var emptyColor = new THREE.Color("black");

  this.setRenderTarget = function( renderTarget ) {

    this.renderTarget = renderTarget;
		RTMaterial.uniforms[ "texid" ].value = renderTarget;

  }
  this.setOutputTarget = function( outputTarget ) {

    this.outputTarget = outputTarget;

  }

	// Render target
	var RTParams = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
	//var renderTarget = new THREE.WebGLRenderTarget( HMD.hResolution / 2, HMD.vResolution, RTParams );
	var RTMaterial = new THREE.ShaderMaterial( {
		uniforms: {
			"texid": { type: "t", value: this.renderTarget },
			"scale": { type: "v2", value: new THREE.Vector2(1.0,1.0) },
			"scaleIn": { type: "v2", value: new THREE.Vector2(1.0,1.0) },
			"lensCenter": { type: "v2", value: new THREE.Vector2(0.0,0.0) },
			"hmdWarpParam": { type: "v4", value: new THREE.Vector4(1.0,0.0,0.0,0.0) },
			"chromAbParam": { type: "v4", value: new THREE.Vector4(1.0,0.0,0.0,0.0) }
		},
		vertexShader: [
			"varying vec2 vUv;",
			"void main() {",
			" vUv = uv;",
			"	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
			"}"
		].join("\n"),

		fragmentShader: [
			"uniform vec2 scale;",
			"uniform vec2 scaleIn;",
			"uniform vec2 lensCenter;",
			"uniform vec4 hmdWarpParam;",
			'uniform vec4 chromAbParam;',
			"uniform sampler2D texid;",
			"varying vec2 vUv;",
			"void main()",
			"{",
			"  vec2 uv = (vUv*2.0)-1.0;", // range from [0,1] to [-1,1]
			"  vec2 theta = (uv-lensCenter)*scaleIn;",
			"  float rSq = theta.x*theta.x + theta.y*theta.y;",
			"  vec2 rvector = theta*(hmdWarpParam.x + hmdWarpParam.y*rSq + hmdWarpParam.z*rSq*rSq + hmdWarpParam.w*rSq*rSq*rSq);",
			'  vec2 rBlue = rvector * (chromAbParam.z + chromAbParam.w * rSq);',
			"  vec2 tcBlue = (lensCenter + scale * rBlue);",
			"  tcBlue = (tcBlue+1.0)/2.0;", // range from [-1,1] to [0,1]
			"  if (any(bvec2(clamp(tcBlue, vec2(0.0,0.0), vec2(1.0,1.0))-tcBlue))) {",
			"    gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);",
			"    return;}",
			"  vec2 tcGreen = lensCenter + scale * rvector;",
			"  tcGreen = (tcGreen+1.0)/2.0;", // range from [-1,1] to [0,1]
			"  vec2 rRed = rvector * (chromAbParam.x + chromAbParam.y * rSq);",
			"  vec2 tcRed = lensCenter + scale * rRed;",
			"  tcRed = (tcRed+1.0)/2.0;", // range from [-1,1] to [0,1]
			"  gl_FragColor = vec4(texture2D(texid, tcRed).r, texture2D(texid, tcGreen).g, texture2D(texid, tcBlue).b, 1);",
			"}"
		].join("\n")
	} );

	var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 1, 2 ), RTMaterial );
  mesh.position.x = -.5;

	// Final scene
	var finalScene = new THREE.Scene();
	finalScene.add( oCamera );
	finalScene.add( mesh );

  var left = {}, right = {};
  var distScale = 1.0;

	this.setHMD = function(v) {
		HMD = v;
		// Compute aspect ratio and FOV
		var aspect = HMD.hResolution / (2*HMD.vResolution);

		// Fov is normally computed with:
		//   THREE.Math.radToDeg( 2*Math.atan2(HMD.vScreenSize,2*HMD.eyeToScreenDistance) );
		// But with lens distortion it is increased (see Oculus SDK Documentation)
		var r = -1.0 - (4 * (HMD.hScreenSize/4 - HMD.lensSeparationDistance/2) / HMD.hScreenSize);
		distScale = (HMD.distortionK[0] + HMD.distortionK[1] * Math.pow(r,2) + HMD.distortionK[2] * Math.pow(r,4) + HMD.distortionK[3] * Math.pow(r,6));
		var fov = THREE.Math.radToDeg(2*Math.atan2(HMD.vScreenSize*distScale, 2*HMD.eyeToScreenDistance));

		// Compute camera projection matrices
		var proj = (new THREE.Matrix4()).makePerspective( fov, aspect, 0.3, 10000 );
		var h = 4 * (HMD.hScreenSize/4 - HMD.interpupillaryDistance/2) / HMD.hScreenSize;
		left.proj = ((new THREE.Matrix4()).makeTranslation( h, 0.0, 0.0 )).multiply(proj);
		right.proj = ((new THREE.Matrix4()).makeTranslation( -h, 0.0, 0.0 )).multiply(proj);

		// Compute camera transformation matrices
		left.tranform = (new THREE.Matrix4()).makeTranslation( -worldFactor * HMD.interpupillaryDistance/2, 0.0, 0.0 );
		right.tranform = (new THREE.Matrix4()).makeTranslation( worldFactor * HMD.interpupillaryDistance/2, 0.0, 0.0 );

		// Compute Viewport
		left.viewport = [0, 0, HMD.hResolution/2, HMD.vResolution];
		right.viewport = [HMD.hResolution/2, 0, HMD.hResolution/2, HMD.vResolution];

		// Distortion shader parameters
		var lensShift = 4 * (HMD.hScreenSize/4 - HMD.lensSeparationDistance/2) / HMD.hScreenSize;
		left.lensCenter = new THREE.Vector2(lensShift, 0.0);
		right.lensCenter = new THREE.Vector2(-lensShift, 0.0);

		RTMaterial.uniforms['hmdWarpParam'].value = new THREE.Vector4(HMD.distortionK[0], HMD.distortionK[1], HMD.distortionK[2], HMD.distortionK[3]);
		RTMaterial.uniforms['chromAbParam'].value = new THREE.Vector4(HMD.chromaAbParameter[0], HMD.chromaAbParameter[1], HMD.chromaAbParameter[2], HMD.chromaAbParameter[3]);
		RTMaterial.uniforms['scaleIn'].value = new THREE.Vector2(1.0,1.0/aspect);
		RTMaterial.uniforms['scale'].value = new THREE.Vector2(1.0/distScale, 1.0*aspect/distScale);

		// Create render target
		if ( this.renderTarget ) this.renderTarget.dispose();
		//renderTarget = new THREE.WebGLRenderTarget( HMD.hResolution*distScale/2, HMD.vResolution*distScale, RTParams );
    this.setRenderTarget(new THREE.WebGLRenderTarget( HMD.hResolution*distScale/2, HMD.vResolution*distScale, RTParams ));
    this.setOutputTarget(options && options.renderTarget ? options.renderTarget : null);

	}
	this.getHMD = function() {return HMD};

	this.setHMD(HMD);

	this.setSize = function ( width, height ) {
		left.viewport = [width/2 - HMD.hResolution/2, height/2 - HMD.vResolution/2, HMD.hResolution/2, HMD.vResolution];
		right.viewport = [width/2, height/2 - HMD.vResolution/2, HMD.hResolution/2, HMD.vResolution];

		renderer.setSize( width, height );
	};

	this.render = function ( scene, camera ) {
		var cc = renderer.getClearColor().clone();

		// Clear
		//renderer.setClearColor(emptyColor);
		//renderer.clear();
		//renderer.setClearColor(cc);

		// camera parameters
		if (camera.matrixAutoUpdate) camera.updateMatrix();

		// Render left
		this.preLeftRender();
    mesh.position.x = -.5;

		pCamera.projectionMatrix.copy(left.proj);

		pCamera.matrix.copy(camera.matrix).multiply(left.tranform);
		pCamera.matrixWorldNeedsUpdate = true;

		if (pCamera.parent && pCamera.parent != camera.parent) {
			pCamera.parent.remove(pCamera);
		}
		if (camera.parent && camera.parent != pCamera.parent) {
			camera.parent.add(pCamera);
		}

		renderer.setViewport(left.viewport[0], left.viewport[1], left.viewport[2], left.viewport[3]);

		RTMaterial.uniforms['lensCenter'].value = left.lensCenter;
		renderer.render( scene, pCamera, this.renderTarget, true );
		renderer.render( finalScene, oCamera, this.outputTarget );

		// Render right
		this.preRightRender();
    mesh.position.x = .5;

		pCamera.projectionMatrix.copy(right.proj);

		pCamera.matrix.copy(camera.matrix).multiply(right.tranform);
		pCamera.matrixWorldNeedsUpdate = true;

		renderer.setViewport(right.viewport[0], right.viewport[1], right.viewport[2], right.viewport[3]);

		RTMaterial.uniforms['lensCenter'].value = right.lensCenter;

		renderer.render( scene, pCamera, this.renderTarget, true );
		renderer.render( finalScene, oCamera, this.outputTarget );

		renderer.setViewport(left.viewport[0], left.viewport[1], left.viewport[2] * 2, left.viewport[3]);

	};

	this.dispose = function() {
		if ( RTMaterial ) {
			RTMaterial.dispose();
		}
		if ( this.renderTarget ) {
			this.renderTarget.dispose();
		}
	};

};
<commit_msg>Decreased near plane distance for oculus rift cameras<commit_after>/**
 * @author troffmo5 / http://github.com/troffmo5
 *
 * Effect to render the scene in stereo 3d side by side with lens distortion.
 * It is written to be used with the Oculus Rift (http://www.oculusvr.com/) but
 * it works also with other HMD using the same technology
 */

THREE.OculusRiftEffect = function ( renderer, options ) {
	// worldFactor indicates how many units is 1 meter
	var worldFactor = (options && options.worldFactor) ? options.worldFactor: 1.0;

	// Specific HMD parameters
	var HMD = (options && options.HMD) ? options.HMD: {
		// Parameters from the Oculus Rift DK1
		hResolution: window.innerWidth,
		vResolution: window.innerHeight,
		hScreenSize: 0.14976,
		vScreenSize: 0.0936,
		interpupillaryDistance: 0.064,
		lensSeparationDistance: 0.064,
		eyeToScreenDistance: 0.041,
		distortionK : [1.0, 0.22, 0.24, 0.0],
		chromaAbParameter: [ 0.996, -0.004, 1.014, 0.0]
	};

	// Perspective camera
	var pCamera = new THREE.PerspectiveCamera();
	pCamera.matrixAutoUpdate = false;
	pCamera.target = new THREE.Vector3();

	// Orthographic camera
	var oCamera = new THREE.OrthographicCamera( -1, 1, 1, -1, 1, 1000 );
	oCamera.position.z = 1;

	// pre-render hooks
	this.preLeftRender = function() {};
	this.preRightRender = function() {};

  this.renderTarget = false;
  this.outputTarget = false;

	renderer.autoClear = false;
	var emptyColor = new THREE.Color("black");

  this.setRenderTarget = function( renderTarget ) {

    this.renderTarget = renderTarget;
		RTMaterial.uniforms[ "texid" ].value = renderTarget;

  }
  this.setOutputTarget = function( outputTarget ) {

    this.outputTarget = outputTarget;

  }

	// Render target
	var RTParams = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
	//var renderTarget = new THREE.WebGLRenderTarget( HMD.hResolution / 2, HMD.vResolution, RTParams );
	var RTMaterial = new THREE.ShaderMaterial( {
		uniforms: {
			"texid": { type: "t", value: this.renderTarget },
			"scale": { type: "v2", value: new THREE.Vector2(1.0,1.0) },
			"scaleIn": { type: "v2", value: new THREE.Vector2(1.0,1.0) },
			"lensCenter": { type: "v2", value: new THREE.Vector2(0.0,0.0) },
			"hmdWarpParam": { type: "v4", value: new THREE.Vector4(1.0,0.0,0.0,0.0) },
			"chromAbParam": { type: "v4", value: new THREE.Vector4(1.0,0.0,0.0,0.0) }
		},
		vertexShader: [
			"varying vec2 vUv;",
			"void main() {",
			" vUv = uv;",
			"	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
			"}"
		].join("\n"),

		fragmentShader: [
			"uniform vec2 scale;",
			"uniform vec2 scaleIn;",
			"uniform vec2 lensCenter;",
			"uniform vec4 hmdWarpParam;",
			'uniform vec4 chromAbParam;',
			"uniform sampler2D texid;",
			"varying vec2 vUv;",
			"void main()",
			"{",
			"  vec2 uv = (vUv*2.0)-1.0;", // range from [0,1] to [-1,1]
			"  vec2 theta = (uv-lensCenter)*scaleIn;",
			"  float rSq = theta.x*theta.x + theta.y*theta.y;",
			"  vec2 rvector = theta*(hmdWarpParam.x + hmdWarpParam.y*rSq + hmdWarpParam.z*rSq*rSq + hmdWarpParam.w*rSq*rSq*rSq);",
			'  vec2 rBlue = rvector * (chromAbParam.z + chromAbParam.w * rSq);',
			"  vec2 tcBlue = (lensCenter + scale * rBlue);",
			"  tcBlue = (tcBlue+1.0)/2.0;", // range from [-1,1] to [0,1]
			"  if (any(bvec2(clamp(tcBlue, vec2(0.0,0.0), vec2(1.0,1.0))-tcBlue))) {",
			"    gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);",
			"    return;}",
			"  vec2 tcGreen = lensCenter + scale * rvector;",
			"  tcGreen = (tcGreen+1.0)/2.0;", // range from [-1,1] to [0,1]
			"  vec2 rRed = rvector * (chromAbParam.x + chromAbParam.y * rSq);",
			"  vec2 tcRed = lensCenter + scale * rRed;",
			"  tcRed = (tcRed+1.0)/2.0;", // range from [-1,1] to [0,1]
			"  gl_FragColor = vec4(texture2D(texid, tcRed).r, texture2D(texid, tcGreen).g, texture2D(texid, tcBlue).b, 1);",
			"}"
		].join("\n")
	} );

	var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 1, 2 ), RTMaterial );
  mesh.position.x = -.5;

	// Final scene
	var finalScene = new THREE.Scene();
	finalScene.add( oCamera );
	finalScene.add( mesh );

  var left = {}, right = {};
  var distScale = 1.0;

	this.setHMD = function(v) {
		HMD = v;
		// Compute aspect ratio and FOV
		var aspect = HMD.hResolution / (2*HMD.vResolution);

		// Fov is normally computed with:
		//   THREE.Math.radToDeg( 2*Math.atan2(HMD.vScreenSize,2*HMD.eyeToScreenDistance) );
		// But with lens distortion it is increased (see Oculus SDK Documentation)
		var r = -1.0 - (4 * (HMD.hScreenSize/4 - HMD.lensSeparationDistance/2) / HMD.hScreenSize);
		distScale = (HMD.distortionK[0] + HMD.distortionK[1] * Math.pow(r,2) + HMD.distortionK[2] * Math.pow(r,4) + HMD.distortionK[3] * Math.pow(r,6));
		var fov = THREE.Math.radToDeg(2*Math.atan2(HMD.vScreenSize*distScale, 2*HMD.eyeToScreenDistance));

		// Compute camera projection matrices
		var proj = (new THREE.Matrix4()).makePerspective( fov, aspect, 0.1, 10000 );
		var h = 4 * (HMD.hScreenSize/4 - HMD.interpupillaryDistance/2) / HMD.hScreenSize;
		left.proj = ((new THREE.Matrix4()).makeTranslation( h, 0.0, 0.0 )).multiply(proj);
		right.proj = ((new THREE.Matrix4()).makeTranslation( -h, 0.0, 0.0 )).multiply(proj);

		// Compute camera transformation matrices
		left.tranform = (new THREE.Matrix4()).makeTranslation( -worldFactor * HMD.interpupillaryDistance/2, 0.0, 0.0 );
		right.tranform = (new THREE.Matrix4()).makeTranslation( worldFactor * HMD.interpupillaryDistance/2, 0.0, 0.0 );

		// Compute Viewport
		left.viewport = [0, 0, HMD.hResolution/2, HMD.vResolution];
		right.viewport = [HMD.hResolution/2, 0, HMD.hResolution/2, HMD.vResolution];

		// Distortion shader parameters
		var lensShift = 4 * (HMD.hScreenSize/4 - HMD.lensSeparationDistance/2) / HMD.hScreenSize;
		left.lensCenter = new THREE.Vector2(lensShift, 0.0);
		right.lensCenter = new THREE.Vector2(-lensShift, 0.0);

		RTMaterial.uniforms['hmdWarpParam'].value = new THREE.Vector4(HMD.distortionK[0], HMD.distortionK[1], HMD.distortionK[2], HMD.distortionK[3]);
		RTMaterial.uniforms['chromAbParam'].value = new THREE.Vector4(HMD.chromaAbParameter[0], HMD.chromaAbParameter[1], HMD.chromaAbParameter[2], HMD.chromaAbParameter[3]);
		RTMaterial.uniforms['scaleIn'].value = new THREE.Vector2(1.0,1.0/aspect);
		RTMaterial.uniforms['scale'].value = new THREE.Vector2(1.0/distScale, 1.0*aspect/distScale);

		// Create render target
		if ( this.renderTarget ) this.renderTarget.dispose();
		//renderTarget = new THREE.WebGLRenderTarget( HMD.hResolution*distScale/2, HMD.vResolution*distScale, RTParams );
    this.setRenderTarget(new THREE.WebGLRenderTarget( HMD.hResolution*distScale/2, HMD.vResolution*distScale, RTParams ));
    this.setOutputTarget(options && options.renderTarget ? options.renderTarget : null);

	}
	this.getHMD = function() {return HMD};

	this.setHMD(HMD);

	this.setSize = function ( width, height ) {
		left.viewport = [width/2 - HMD.hResolution/2, height/2 - HMD.vResolution/2, HMD.hResolution/2, HMD.vResolution];
		right.viewport = [width/2, height/2 - HMD.vResolution/2, HMD.hResolution/2, HMD.vResolution];

		renderer.setSize( width, height );
	};

	this.render = function ( scene, camera ) {
		var cc = renderer.getClearColor().clone();

		// Clear
		//renderer.setClearColor(emptyColor);
		//renderer.clear();
		//renderer.setClearColor(cc);

		// camera parameters
		if (camera.matrixAutoUpdate) camera.updateMatrix();

		// Render left
		this.preLeftRender();
    mesh.position.x = -.5;

		pCamera.projectionMatrix.copy(left.proj);

		pCamera.matrix.copy(camera.matrix).multiply(left.tranform);
		pCamera.matrixWorldNeedsUpdate = true;

		if (pCamera.parent && pCamera.parent != camera.parent) {
			pCamera.parent.remove(pCamera);
		}
		if (camera.parent && camera.parent != pCamera.parent) {
			camera.parent.add(pCamera);
		}
    pCamera.near = camera.near;
    pCamera.far = camera.far;

		renderer.setViewport(left.viewport[0], left.viewport[1], left.viewport[2], left.viewport[3]);

		RTMaterial.uniforms['lensCenter'].value = left.lensCenter;
		renderer.render( scene, pCamera, this.renderTarget, true );
		renderer.render( finalScene, oCamera, this.outputTarget );

		// Render right
		this.preRightRender();
    mesh.position.x = .5;

		pCamera.projectionMatrix.copy(right.proj);

		pCamera.matrix.copy(camera.matrix).multiply(right.tranform);
		pCamera.matrixWorldNeedsUpdate = true;

		renderer.setViewport(right.viewport[0], right.viewport[1], right.viewport[2], right.viewport[3]);

		RTMaterial.uniforms['lensCenter'].value = right.lensCenter;

		renderer.render( scene, pCamera, this.renderTarget, true );
		renderer.render( finalScene, oCamera, this.outputTarget );

		renderer.setViewport(left.viewport[0], left.viewport[1], left.viewport[2] * 2, left.viewport[3]);

	};

	this.dispose = function() {
		if ( RTMaterial ) {
			RTMaterial.dispose();
		}
		if ( this.renderTarget ) {
			this.renderTarget.dispose();
		}
	};

};
<|endoftext|>


<commit_before>var Widgets = {
    init: function (selecteur) {
        $(function () {
            Widgets.initMoreWidgets($('.widget', selecteur || document));
            Widgets.initScrollable(selecteur);
        });
    },
    //Deps: ['scrollable']
    initScrollable: function (selecteur) {
        var targets = $(".scrollable", selecteur || document);
        if (targets.length) {
            targets.mCustomScrollbar({
                axis: "y",
                theme: "minimal-dark",
                autoHideScrollbar: true,
                callbacks: {
                    onScroll: function(){
                        console.log('SCROLLING');
                        App.initLazyLoading(selecteur);
                    }
                }
            });
        }
    },
    //Deps: ['scrollable']
    initMoreWidgets: function (elems) {
        elems.each(function () {
            var container = $(this);
            var containerActions = container.find('.panel-footer');
            var moreContentLink = container.find('.more-content');
            var containerBody = moreContentLink.parent();

            if (!moreContentLink.length) {
                containerActions.html('');
            } else {
                var newMoreContentLink = moreContentLink.clone();
                containerActions.html(newMoreContentLink);
                moreContentLink.remove();

                newMoreContentLink.unbind('click').click(function (e) {
                    var btn = $(this);
                    if(btn.attr('disabled')) {
                        return false;
                    }
                    btn.attr("disabled", true).prepend(" ");
                    $.get(btn.attr('href')).done(function (content) {
                        btn.remove();
                        containerBody.append(content);
                        container.find('.scrollable').mCustomScrollbar("scrollTo", "bottom");
                        Widgets.initMoreWidgets(container);
                        App.initComponents(container);
                    });

                    e.preventDefault();
                    return false;
                });
            }
        });
    }
};

Widgets.init();
<commit_msg>Fix console.log sur JS<commit_after>var Widgets = {
    init: function (selecteur) {
        $(function () {
            Widgets.initMoreWidgets($('.widget', selecteur || document));
            Widgets.initScrollable(selecteur);
        });
    },
    //Deps: ['scrollable']
    initScrollable: function (selecteur) {
        var targets = $(".scrollable", selecteur || document);
        if (targets.length) {
            targets.mCustomScrollbar({
                axis: "y",
                theme: "minimal-dark",
                autoHideScrollbar: true,
                callbacks: {
                    onScroll: function(){
                        App.initLazyLoading(selecteur);
                    }
                }
            });
        }
    },
    //Deps: ['scrollable']
    initMoreWidgets: function (elems) {
        elems.each(function () {
            var container = $(this);
            var containerActions = container.find('.panel-footer');
            var moreContentLink = container.find('.more-content');
            var containerBody = moreContentLink.parent();

            if (!moreContentLink.length) {
                containerActions.html('');
            } else {
                var newMoreContentLink = moreContentLink.clone();
                containerActions.html(newMoreContentLink);
                moreContentLink.remove();

                newMoreContentLink.unbind('click').click(function (e) {
                    var btn = $(this);
                    if(btn.attr('disabled')) {
                        return false;
                    }
                    btn.attr("disabled", true).prepend(" ");
                    $.get(btn.attr('href')).done(function (content) {
                        btn.remove();
                        containerBody.append(content);
                        container.find('.scrollable').mCustomScrollbar("scrollTo", "bottom");
                        Widgets.initMoreWidgets(container);
                        App.initComponents(container);
                    });

                    e.preventDefault();
                    return false;
                });
            }
        });
    }
};

Widgets.init();
<|endoftext|>


<commit_before>$(document).ready(function() {
    // Get all differents sections
    var sections = new Array();
    var sectionActive = parseInt(window.location.hash.substring(8));
    if (!sectionActive) {
        sectionActive = 0;
        window.location.hash = '#section0';
    }
    $('[data-section]').each(function () {
        var challenger = $(this).attr('data-section');
        if (sections.indexOf(challenger) === -1) {
            sections.push(challenger);
        }
    });
    // Créate the nav
    $('.form-block.form-with-sections > form > div').prepend('

');
    // Wrap all form input group of the same section into a common wrapper
    sections.forEach(function (name, id) {
        var classAttr = 'form-section tab-pane fade';
        var classNav = 'nav-section';
        if (sectionActive === id) {
            classAttr += ' active in';
            classNav += ' active';
        }
        $('[data-section='+name+']').closest('.form_row.form-group').wrapAll(
            '

'
        );
        $('.nav-sections').append(
            '
'+name+'
'
        );
    });
    $('.form-section').wrapAll('

');
    // Handle url tab
    $(document).on('shown.bs.tab', '[data-toggle=tab]', function(event) {
        window.location.hash = $(event.target).attr('href');
    });
});
<commit_msg>Enforce context test<commit_after>$(document).ready(function() {
    if ($('.form-with-sections').length) {
        // Get all differents sections
        var sections = new Array();
        var sectionActive = parseInt(window.location.hash.substring(8));
        if (!sectionActive) {
            sectionActive = 0;
            window.location.hash = '#section0';
        }
        $('[data-section]').each(function () {
            var challenger = $(this).attr('data-section');
            if (sections.indexOf(challenger) === -1) {
                sections.push(challenger);
            }
        });
        // Créate the nav
        $('form > div').prepend('

');
        // Wrap all form input group of the same section into a common wrapper
        sections.forEach(function (name, id) {
            var classAttr = 'form-section tab-pane fade';
            var classNav = 'nav-section';
            if (sectionActive === id) {
                classAttr += ' active in';
                classNav += ' active';
            }
            $('[data-section='+name+']').closest('.form_row.form-group').wrapAll(
                '

'
            );
            $('.nav-sections').append(
                '
'+name+'
'
            );
        });
        $('.form-section').wrapAll('

');
        // Handle url tab
        $(document).on('shown.bs.tab', '[data-toggle=tab]', function(event) {
            window.location.hash = $(event.target).attr('href');
        });
    }
});
<|endoftext|>


<commit_before>'use strict';
var async = require("async");
var utils = require("../../../utils/utils.js");

function checkIfError(soajs, mainCb, data, cb) {
	utils.checkErrorReturn(soajs, mainCb, data, cb);
}

var BL = {
	model: null,

	"list": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {

					var options = utils.buildDeployerOptions(envRecord, soajs, BL);

					deployer.listSecrets(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	},

	"add": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {
					var options = utils.buildDeployerOptions(envRecord, soajs, BL);
					options.params = {
						name: soajs.inputmaskData.name,
						data: {}
					};
					options.params.data[soajs.inputmaskData.name] =  soajs.inputmaskData.data;

					if (soajs.inputmaskData.type){
						options.params.type = soajs.inputmaskData.type;
					}
					deployer.createSecret(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	},

	"delete": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {

					var options = utils.buildDeployerOptions(envRecord, soajs, BL);
					options.params = {
						name: soajs.inputmaskData.name,
					};
					deployer.deleteSecret(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	},

	"get": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {

					var options = utils.buildDeployerOptions(envRecord, soajs, BL);
					options.params = {
						name: soajs.inputmaskData.name,
					};
					deployer.getSecret(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	}
};

module.exports = {
	"init": function (modelName, cb) {
		var modelPath;

		if (!modelName) {
			return cb(new Error("No Model Requested!"));
		}

		modelPath = __dirname + "/../../../models/" + modelName + ".js";
		return requireModel(modelPath, cb);

		/**
		 * checks if model file exists, requires it and returns it.
		 * @param filePath
		 * @param cb
		 */
		function requireModel(filePath, cb) {
			//check if file exist. if not return error
			fs.exists(filePath, function (exists) {
				if (!exists) {
					return cb(new Error("Requested Model Not Found!"));
				}

				BL.model = require(filePath);
				return cb(null, BL);
			});
		}
	}
};

<commit_msg>minor fix<commit_after>'use strict';
var async = require("async");
var utils = require("../../../utils/utils.js");
var fs = require('fs');

function checkIfError(soajs, mainCb, data, cb) {
	utils.checkErrorReturn(soajs, mainCb, data, cb);
}

var BL = {
	model: null,

	"list": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {

					var options = utils.buildDeployerOptions(envRecord, soajs, BL);

					deployer.listSecrets(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	},

	"add": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {
					var options = utils.buildDeployerOptions(envRecord, soajs, BL);
					options.params = {
						name: soajs.inputmaskData.name,
						data: {}
					};
					options.params.data[soajs.inputmaskData.name] =  soajs.inputmaskData.data;

					if (soajs.inputmaskData.type){
						options.params.type = soajs.inputmaskData.type;
					}
					deployer.createSecret(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	},

	"delete": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {

					var options = utils.buildDeployerOptions(envRecord, soajs, BL);
					options.params = {
						name: soajs.inputmaskData.name,
					};
					deployer.deleteSecret(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	},

	"get": function (config, soajs, deployer, cbMain) {
		utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env.toUpperCase(), function (error, envRecord) {
			checkIfError(soajs, cbMain, {
				config: config,
				error: error || !envRecord,
				code: 600
			}, function () {
				checkIfError(soajs, cbMain, {
					config: config,
					error: !envRecord.deployer.type || !envRecord.deployer.selected || envRecord.deployer.type === 'manual',
					code: 743
				}, function () {

					var options = utils.buildDeployerOptions(envRecord, soajs, BL);
					options.params = {
						name: soajs.inputmaskData.name,
					};
					deployer.getSecret(options, function (error) {
						checkIfError(soajs, cbMain, {config: config, error: error}, function () {
							return cbMain(null, true);
						});
					});
				});
			});
		});
	}
};

module.exports = {
	"init": function (modelName, cb) {
		var modelPath;

		if (!modelName) {
			return cb(new Error("No Model Requested!"));
		}

		modelPath = __dirname + "/../../../models/" + modelName + ".js";
		return requireModel(modelPath, cb);

		/**
		 * checks if model file exists, requires it and returns it.
		 * @param filePath
		 * @param cb
		 */
		function requireModel(filePath, cb) {
			//check if file exist. if not return error
			fs.exists(filePath, function (exists) {
				if (!exists) {
					return cb(new Error("Requested Model Not Found!"));
				}

				BL.model = require(filePath);
				return cb(null, BL);
			});
		}
	}
};
<|endoftext|>


<commit_before>/**
@module ember
@submodule ember-runtime
*/

// Ember.lookup, Ember.BOOTED, Ember.deprecate, Ember.NAME_KEY, Ember.anyUnprocessedMixins
import Ember from "ember-metal/core";
import { get } from "ember-metal/property_get";
import { indexOf } from "ember-metal/array";
import {
  GUID_KEY,
  guidFor
} from "ember-metal/utils";
import { Mixin } from "ember-metal/mixin";

import EmberObject from "ember-runtime/system/object";

/**
  A Namespace is an object usually used to contain other objects or methods
  such as an application or framework. Create a namespace anytime you want
  to define one of these new containers.

  # Example Usage

  ```javascript
  MyFramework = Ember.Namespace.create({
    VERSION: '1.0.0'
  });
  ```

  @class Namespace
  @namespace Ember
  @extends Ember.Object
*/
var Namespace = EmberObject.extend({
  isNamespace: true,

  init: function() {
    Namespace.NAMESPACES.push(this);
    Namespace.PROCESSED = false;
  },

  toString: function() {
    var name = get(this, 'name');
    if (name) { return name; }

    findNamespaces();
    return this[NAME_KEY];
  },

  nameClasses: function() {
    processNamespace([this.toString()], this, {});
  },

  destroy: function() {
    var namespaces = Namespace.NAMESPACES,
        toString = this.toString();

    if (toString) {
      Ember.lookup[toString] = undefined;
      delete Namespace.NAMESPACES_BY_ID[toString];
    }
    namespaces.splice(indexOf.call(namespaces, this), 1);
    this._super();
  }
});

Namespace.reopenClass({
  NAMESPACES: [Ember],
  NAMESPACES_BY_ID: {},
  PROCESSED: false,
  processAll: processAllNamespaces,
  byName: function(name) {
    if (!Ember.BOOTED) {
      processAllNamespaces();
    }

    return NAMESPACES_BY_ID[name];
  }
});

var NAMESPACES_BY_ID = Namespace.NAMESPACES_BY_ID;

var hasOwnProp = ({}).hasOwnProperty;

function processNamespace(paths, root, seen) {
  var idx = paths.length;

  NAMESPACES_BY_ID[paths.join('.')] = root;

  // Loop over all of the keys in the namespace, looking for classes
  for(var key in root) {
    if (!hasOwnProp.call(root, key)) { continue; }
    var obj = root[key];

    // If we are processing the `Ember` namespace, for example, the
    // `paths` will start with `["Ember"]`. Every iteration through
    // the loop will update the **second** element of this list with
    // the key, so processing `Ember.View` will make the Array
    // `['Ember', 'View']`.
    paths[idx] = key;

    // If we have found an unprocessed class
    if (obj && obj.toString === classToString) {
      // Replace the class' `toString` with the dot-separated path
      // and set its `NAME_KEY`
      obj.toString = makeToString(paths.join('.'));
      obj[NAME_KEY] = paths.join('.');

    // Support nested namespaces
    } else if (obj && obj.isNamespace) {
      // Skip aliased namespaces
      if (seen[guidFor(obj)]) { continue; }
      seen[guidFor(obj)] = true;

      // Process the child namespace
      processNamespace(paths, obj, seen);
    }
  }

  paths.length = idx; // cut out last item
}

var STARTS_WITH_UPPERCASE = /^[A-Z]/;

function findNamespaces() {
  var lookup = Ember.lookup, obj, isNamespace;

  if (Namespace.PROCESSED) { return; }

  for (var prop in lookup) {
    // Only process entities that start with uppercase A-Z
    if (!STARTS_WITH_UPPERCASE.test(prop)) { continue; }

    // Unfortunately, some versions of IE don't support window.hasOwnProperty
    if (lookup.hasOwnProperty && !lookup.hasOwnProperty(prop)) { continue; }

    // At times we are not allowed to access certain properties for security reasons.
    // There are also times where even if we can access them, we are not allowed to access their properties.
    try {
      obj = lookup[prop];
      isNamespace = obj && obj.isNamespace;
    } catch (e) {
      continue;
    }

    if (isNamespace) {
      obj[NAME_KEY] = prop;
    }
  }
}

var NAME_KEY = Ember.NAME_KEY = GUID_KEY + '_name';

function superClassString(mixin) {
  var superclass = mixin.superclass;
  if (superclass) {
    if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; }
    else { return superClassString(superclass); }
  } else {
    return;
  }
}

function classToString() {
  if (!Ember.BOOTED && !this[NAME_KEY]) {
    processAllNamespaces();
  }

  var ret;

  if (this[NAME_KEY]) {
    ret = this[NAME_KEY];
  } else if (this._toString) {
    ret = this._toString;
  } else {
    var str = superClassString(this);
    if (str) {
      ret = "(subclass of " + str + ")";
    } else {
      ret = "(unknown mixin)";
    }
    this.toString = makeToString(ret);
  }

  return ret;
}

function processAllNamespaces() {
  var unprocessedNamespaces = !Namespace.PROCESSED,
      unprocessedMixins = Ember.anyUnprocessedMixins;

  if (unprocessedNamespaces) {
    findNamespaces();
    Namespace.PROCESSED = true;
  }

  if (unprocessedNamespaces || unprocessedMixins) {
    var namespaces = Namespace.NAMESPACES, namespace;
    for (var i=0, l=namespaces.length; i<l; i++) {
      namespace = namespaces[i];
      processNamespace([namespace.toString()], namespace, {});
    }

    Ember.anyUnprocessedMixins = false;
  }
}

function makeToString(ret) {
  return function() { return ret; };
}

Mixin.prototype.toString = classToString; // ES6TODO: altering imported objects. SBB.

export default Namespace;
<commit_msg>[Bugfix beta] keep the try/catch deopt isolated.<commit_after>/**
@module ember
@submodule ember-runtime
*/

// Ember.lookup, Ember.BOOTED, Ember.deprecate, Ember.NAME_KEY, Ember.anyUnprocessedMixins
import Ember from "ember-metal/core";
import { get } from "ember-metal/property_get";
import { indexOf } from "ember-metal/array";
import {
  GUID_KEY,
  guidFor
} from "ember-metal/utils";
import { Mixin } from "ember-metal/mixin";

import EmberObject from "ember-runtime/system/object";

/**
  A Namespace is an object usually used to contain other objects or methods
  such as an application or framework. Create a namespace anytime you want
  to define one of these new containers.

  # Example Usage

  ```javascript
  MyFramework = Ember.Namespace.create({
    VERSION: '1.0.0'
  });
  ```

  @class Namespace
  @namespace Ember
  @extends Ember.Object
*/
var Namespace = EmberObject.extend({
  isNamespace: true,

  init: function() {
    Namespace.NAMESPACES.push(this);
    Namespace.PROCESSED = false;
  },

  toString: function() {
    var name = get(this, 'name');
    if (name) { return name; }

    findNamespaces();
    return this[NAME_KEY];
  },

  nameClasses: function() {
    processNamespace([this.toString()], this, {});
  },

  destroy: function() {
    var namespaces = Namespace.NAMESPACES,
        toString = this.toString();

    if (toString) {
      Ember.lookup[toString] = undefined;
      delete Namespace.NAMESPACES_BY_ID[toString];
    }
    namespaces.splice(indexOf.call(namespaces, this), 1);
    this._super();
  }
});

Namespace.reopenClass({
  NAMESPACES: [Ember],
  NAMESPACES_BY_ID: {},
  PROCESSED: false,
  processAll: processAllNamespaces,
  byName: function(name) {
    if (!Ember.BOOTED) {
      processAllNamespaces();
    }

    return NAMESPACES_BY_ID[name];
  }
});

var NAMESPACES_BY_ID = Namespace.NAMESPACES_BY_ID;

var hasOwnProp = ({}).hasOwnProperty;

function processNamespace(paths, root, seen) {
  var idx = paths.length;

  NAMESPACES_BY_ID[paths.join('.')] = root;

  // Loop over all of the keys in the namespace, looking for classes
  for(var key in root) {
    if (!hasOwnProp.call(root, key)) { continue; }
    var obj = root[key];

    // If we are processing the `Ember` namespace, for example, the
    // `paths` will start with `["Ember"]`. Every iteration through
    // the loop will update the **second** element of this list with
    // the key, so processing `Ember.View` will make the Array
    // `['Ember', 'View']`.
    paths[idx] = key;

    // If we have found an unprocessed class
    if (obj && obj.toString === classToString) {
      // Replace the class' `toString` with the dot-separated path
      // and set its `NAME_KEY`
      obj.toString = makeToString(paths.join('.'));
      obj[NAME_KEY] = paths.join('.');

    // Support nested namespaces
    } else if (obj && obj.isNamespace) {
      // Skip aliased namespaces
      if (seen[guidFor(obj)]) { continue; }
      seen[guidFor(obj)] = true;

      // Process the child namespace
      processNamespace(paths, obj, seen);
    }
  }

  paths.length = idx; // cut out last item
}

var STARTS_WITH_UPPERCASE = /^[A-Z]/;

function tryIsNamespace(lookup, prop) {
  try {
    var obj = lookup[prop];
    return obj && obj.isNamespace && obj;
  } catch (e) {
    // continue
  }
}

function findNamespaces() {
  var lookup = Ember.lookup, obj, isNamespace;

  if (Namespace.PROCESSED) { return; }

  for (var prop in lookup) {
    // Only process entities that start with uppercase A-Z
    if (!STARTS_WITH_UPPERCASE.test(prop)) { continue; }

    // Unfortunately, some versions of IE don't support window.hasOwnProperty
    if (lookup.hasOwnProperty && !lookup.hasOwnProperty(prop)) { continue; }

    // At times we are not allowed to access certain properties for security reasons.
    // There are also times where even if we can access them, we are not allowed to access their properties.
    obj = tryIsNamespace(lookup, prop);
    if (obj) {
      obj[NAME_KEY] = prop;
    }
  }
}

var NAME_KEY = Ember.NAME_KEY = GUID_KEY + '_name';

function superClassString(mixin) {
  var superclass = mixin.superclass;
  if (superclass) {
    if (superclass[NAME_KEY]) { return superclass[NAME_KEY]; }
    else { return superClassString(superclass); }
  } else {
    return;
  }
}

function classToString() {
  if (!Ember.BOOTED && !this[NAME_KEY]) {
    processAllNamespaces();
  }

  var ret;

  if (this[NAME_KEY]) {
    ret = this[NAME_KEY];
  } else if (this._toString) {
    ret = this._toString;
  } else {
    var str = superClassString(this);
    if (str) {
      ret = "(subclass of " + str + ")";
    } else {
      ret = "(unknown mixin)";
    }
    this.toString = makeToString(ret);
  }

  return ret;
}

function processAllNamespaces() {
  var unprocessedNamespaces = !Namespace.PROCESSED,
      unprocessedMixins = Ember.anyUnprocessedMixins;

  if (unprocessedNamespaces) {
    findNamespaces();
    Namespace.PROCESSED = true;
  }

  if (unprocessedNamespaces || unprocessedMixins) {
    var namespaces = Namespace.NAMESPACES, namespace;
    for (var i=0, l=namespaces.length; i<l; i++) {
      namespace = namespaces[i];
      processNamespace([namespace.toString()], namespace, {});
    }

    Ember.anyUnprocessedMixins = false;
  }
}

function makeToString(ret) {
  return function() { return ret; };
}

Mixin.prototype.toString = classToString; // ES6TODO: altering imported objects. SBB.

export default Namespace;
<|endoftext|>


<commit_before>#!/usr/bin/env node

// --------------------------------------------------------------------------------------
const database = require( '../db' );
const failed_logins = require('../cron/failed_logins.js');
const invalid_records = require('../cron/invalid_records.js');
const mac_count = require('../cron/mac_count.js');
const roaming = require('../cron/roaming.js');
const users_mac = require('../cron/users_mac.js');
// --------------------------------------------------------------------------------------
failed_logins.process_old_data(database);
invalid_records.process_old_data(database);
mac_count.process_old_data(database);
roaming.process_old_data(database);
users_mac.process_old_data(database);
// --------------------------------------------------------------------------------------
<commit_msg>process one task at a time<commit_after>#!/usr/bin/env node

// --------------------------------------------------------------------------------------
const database = require( '../db' );
const async = require( 'async' );
const failed_logins = require('../cron/failed_logins.js');
const invalid_records = require('../cron/invalid_records.js');
const mac_count = require('../cron/mac_count.js');
const roaming = require('../cron/roaming.js');
const users_mac = require('../cron/users_mac.js');
// --------------------------------------------------------------------------------------
// launch all tasks in defined order
// every task is launched after previous is finished
async.series([
  function(callback) {
    database.connect();
    callback(null, null);
  },
  function(callback) {
    failed_logins.process_old_data(database, callback);
  },
  function(callback) {
    failed_logins.process_old_data(database, callback);
  },
  function(callback) {
    invalid_records.process_old_data(database, callback);
  },
  function(callback) {
    mac_count.process_old_data(database, callback);
  },
  function(callback) {
    roaming.process_old_data(database, callback);
  },
  function(callback) {
    users_mac.process_old_data(database, callback);
  }
  ],
  function(err, results) {
    console.log("processing of old data is done");
    database.disconnect();
});
// --------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>var path = require('path'),
    passError = require('../util/passError'),
    assets = require('../assets'),
    relations = require('../relations'),
    query = require('../query');

module.exports = function (queryObj) {
    return function addCacheManifestSinglePage(assetGraph) {
        assetGraph.findAssets(queryObj).forEach(function (htmlAsset) {
            // Look for an existing manifests for htmlAsset:
            var manifest,
                existingManifestRelations = assetGraph.findRelations({
                    from: htmlAsset,
                    type: 'HtmlCacheManifest'
                });
            if (existingManifestRelations.length === 1) {
                manifest = existingManifestRelations[0].to;
            } else if (existingManifestRelations.length > 1) {
                cb(new Error("addCacheManifestSinglePage: Consistency error -- " + htmlAsset + " has more than one cache manifest relation"));
            } else {
                manifest = new assets.CacheManifest({
                    isDirty: true,
                    parseTree: {}
                });
                if (htmlAsset.url) {
                    manifest.url = htmlAsset.url + manifest.defaultExtension;
                } else {
                    manifest.url = assetGraph.root + manifest.id + manifest.defaultExtension;
                }
                assetGraph.addAsset(manifest);
                assetGraph.attachAndAddRelation(new relations.HtmlCacheManifest({
                    from: htmlAsset,
                    to: manifest
                }));
            }

            // Find all assets that can be reached from the Html file and add relations to them from the manifest:

            assetGraph.createSubgraph(htmlAsset).findAssets({url: query.isDefined}).forEach(function (asset) { // FIXME: Query
                // But only if the asset isn't inline and isn't already in the manifest:
                if (asset !== htmlAsset && asset !== manifest && !assetGraph.findRelations({from: manifest, to: asset}).length) {
                    assetGraph.attachAndAddRelation(new relations.CacheManifestEntry({
                        sectionName: 'CACHE',
                        from: manifest,
                        to: asset
                    }));
                }
            });
        });
    };
};
<commit_msg>transforms.addCacheManifestSinglePage: Use traversal.collectAssetsPostOrder instead of AssetGraph.createSubgraph.<commit_after>var path = require('path'),
    passError = require('../util/passError'),
    assets = require('../assets'),
    relations = require('../relations'),
    traversal = require('../traversal'),
    query = require('../query');

module.exports = function (queryObj) {
    return function addCacheManifestSinglePage(assetGraph) {
        assetGraph.findAssets(queryObj).forEach(function (htmlAsset) {
            // Look for an existing manifests for htmlAsset:
            var manifest,
                existingManifestRelations = assetGraph.findRelations({
                    from: htmlAsset,
                    type: 'HtmlCacheManifest'
                });
            if (existingManifestRelations.length === 1) {
                manifest = existingManifestRelations[0].to;
            } else if (existingManifestRelations.length > 1) {
                cb(new Error("addCacheManifestSinglePage: Consistency error -- " + htmlAsset + " has more than one cache manifest relation"));
            } else {
                manifest = new assets.CacheManifest({
                    isDirty: true,
                    parseTree: {}
                });
                if (htmlAsset.url) {
                    manifest.url = htmlAsset.url + manifest.defaultExtension;
                } else {
                    manifest.url = assetGraph.root + manifest.id + manifest.defaultExtension;
                }
                assetGraph.addAsset(manifest);
                assetGraph.attachAndAddRelation(new relations.HtmlCacheManifest({
                    from: htmlAsset,
                    to: manifest
                }));
            }

            // Find all assets that can be reached from the Html file and add relations to them from the manifest:

            traversal.collectAssetsPostOrder(assetGraph, htmlAsset).forEach(function (asset) {
                // Ignore inline assets
                if (!asset.url) {
                    return;
                }
                // But only if the asset isn't inline and isn't already in the manifest:
                if (asset !== htmlAsset && asset !== manifest && !assetGraph.findRelations({from: manifest, to: asset}).length) {
                    assetGraph.attachAndAddRelation(new relations.CacheManifestEntry({
                        sectionName: 'CACHE',
                        from: manifest,
                        to: asset
                    }));
                }
            });
        });
    };
};
<|endoftext|>


<commit_before>import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';

import Analyzer from 'Parser/Core/Analyzer';

import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import calculateEffectiveDamage from 'Parser/Core/calculateEffectiveDamage';

const LANDSLIDE = {
  INCREASE: 0.2,
};

class Landslide extends Analyzer {

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTalent(SPELLS.LANDSLIDE_TALENT.id);
  }

  on_byPlayer_damage(event) {
    if (event.ability.guid!==SPELLS.STORMSTRIKE.id) {
      return;
    }
    if(!this.selectedCombatant.hasBuff(SPELLS.LANDSLIDE_BUFF.id)){
      return;
    }
    this.damageGained += calculateEffectiveDamage(event, LANDSLIDE.INCREASE);
  }

  get damagePercent() {
    return this.owner.getPercentageOfTotalDamageDone(this.damageGained);
  }

  get damagePerSecond() {
    return this.damageGained / (this.owner.fightDuration / 1000);
  }

  statistic() {
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.LANDSLIDE_TALENT.id} />}
        value={`${formatPercentage(this.damagePercent)} %`}
        label="Of total damage"
        tooltip={`Contributed ${formatNumber(this.damagePerSecond)} DPS (${formatNumber(this.damageGained)} total damage).`}
      />
    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(4);
}

export default Landslide;
<commit_msg>Updated Landslide<commit_after>import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';

import Analyzer from 'Parser/Core/Analyzer';

import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import calculateEffectiveDamage from 'Parser/Core/calculateEffectiveDamage';

const LANDSLIDE = {
  INCREASE: 1.0,
};

class Landslide extends Analyzer {

  damageGained=0;

  constructor(...args) {
    super(...args);
    this.active = this.selectedCombatant.hasTalent(SPELLS.LANDSLIDE_TALENT.id);
  }

  on_byPlayer_damage(event) {
    if (event.ability.guid!==SPELLS.STORMSTRIKE_BUFF.id && event.ability.guid!==SPELLS.STORMSTRIKE_OFFHAND.id) {
      return;
    }
    if (!this.selectedCombatant.hasBuff(SPELLS.LANDSLIDE_BUFF.id)){
      return;
    }
    this.damageGained += calculateEffectiveDamage(event, LANDSLIDE.INCREASE);
  }

  get damagePercent() {
    return this.owner.getPercentageOfTotalDamageDone(this.damageGained);
  }

  get damagePerSecond() {
    return this.damageGained / (this.owner.fightDuration / 1000);
  }

  statistic() {
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.LANDSLIDE_TALENT.id} />}
        value={`${formatPercentage(this.damagePercent)} %`}
        label="Of total damage"
        tooltip={`Contributed ${formatNumber(this.damagePerSecond)} DPS (${formatNumber(this.damageGained)} total damage).`}
      />
    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(4);
}

export default Landslide;
<|endoftext|>


<commit_before>/**
 * The main application class. An instance of this class is created by app.js when it calls
 * Ext.application(). This is the ideal place to handle application launch and initialization
 * details.
 */
Ext.define('ContentEditor.Application', {
    extend: 'Ext.app.Application',
    requires: [
        'Emergence.cms.view.Editor'
    ],

    name: 'ContentEditor',

    init: function() {
        Emergence.util.API.setHostname('v1-demo.node0.slate.is');
    },

    launch: function () {
        var me = this,
            dualView = Ext.create('Emergence.cms.view.DualView', {
                renderTo: Ext.getBody()
            });

        // TODO - Launch the application
        Emergence.util.API.request({
            url: '/blog/about',
            success: function(response) {
                dualView.lookupReference('editor').setContentRecord(response.data.data);
            }
        });
    }
});
<commit_msg>use viewport plugin and require correct class in ContentEditor harness app<commit_after>/**
 * The main application class. An instance of this class is created by app.js when it calls
 * Ext.application(). This is the ideal place to handle application launch and initialization
 * details.
 */
Ext.define('ContentEditor.Application', {
    extend: 'Ext.app.Application',
    requires: [
        'Emergence.cms.view.DualView',
        'Ext.plugin.Viewport'
    ],

    name: 'ContentEditor',

    init: function() {
        Emergence.util.API.setHostname('v1-demo.node0.slate.is');
    },

    launch: function () {
        var me = this,
            dualView = Ext.create('Emergence.cms.view.DualView', {
                plugins: 'viewport'
            });

        // TODO - Launch the application
        Emergence.util.API.request({
            url: '/blog/about',
            success: function(response) {
                dualView.lookupReference('editor').setContentRecord(response.data.data);
            }
        });
    }
});
<|endoftext|>


<commit_before>var $ = require('jquery');
var cdb = require('cartodb.js');
var FavMapView = require('./fav_map_view');
var UserInfoView = require('./user_info_view');
var PaginationModel = require('../common/views/pagination/model');
var PaginationView = require('../common/views/pagination/view');
var UserSettingsView = require('../public_common/user_settings_view');
var UserTourView = require('../public_common/user_tour_view');
var UserIndustriesView = require('../public_common/user_industries_view');
var UserResourcesView = require('../public_common/user_resources_view');
var MapCardPreview = require('../common/views/mapcard_preview');
var LikeView = require('../common/views/likes/view');
var ScrollableHeader = require('../common/views/scrollable_header');

$(function() {
  cdb.init(function() {
    cdb.templates.namespace = 'cartodb/';
    cdb.config.set('url_prefix', window.base_url);

    var scrollableHeader = new ScrollableHeader({
      el: $('.js-Navmenu'),
      anchorPoint: 350
    });

    var userTourView = new UserTourView({
      el: $('.js-user-tour'),
    });

    var userIndustriesView = new UserIndustriesView({
      el: $('.js-user-industries'),
    });

    var userResourcesView = new UserResourcesView({
      el: $('.js-user-resources'),
    });

    $(document.body).bind('click', function() {
      cdb.god.trigger('closeDialogs');
    });

    var authenticatedUser = new cdb.open.AuthenticatedUser();
    authenticatedUser.bind('change', function() {
      if (authenticatedUser.get('username')) {
        var user = new cdb.admin.User(authenticatedUser.attributes);
        var userSettingsView = new UserSettingsView({
          el: $('.js-user-settings'),
          model: user
        });
        userSettingsView.render();

        var userDashboardUrl = user.viewUrl().dashboard();
        $('.js-user-info .UserAvatar-img').wrap($('<a>',{
          href: userDashboardUrl
        }));

        $('.js-login').hide();
        $('.js-learn').show();
      }
    });

    var favMapView = new FavMapView(window.favMapViewAttrs);
    favMapView.render();

    var userInfoView = new UserInfoView({
      el: $('.js-user-info')
    });
    userInfoView.render();

    var paginationView = new PaginationView({
      el: '.js-content-footer',
      model: new PaginationModel(window.paginationModelAttrs)
    });
    paginationView.render();

    $('.MapCard').each(function() {

      var vizjson = $(this).data('vizjson-url');
      var zoom    = $(this).data('zoom');

      if (vizjson) {
        var mapCardPreview = new MapCardPreview({
          el: $(this).find('.js-header'),
          height: 220,
          zoom: zoom,
          vizjson: vizjson
        });
        mapCardPreview.load();
      }
    });

    $('.js-likes').each(function() {
      var likeModel = cdb.admin.Like.newByVisData({
        url: !cdb.config.get('url_prefix') ? $(this).attr('href') : '' ,
        likeable: false,
        show_count: $(this).data('show-count') || false,
        show_label: $(this).data('show-label') || false,
        vis_id: $(this).data('vis-id'),
        likes: $(this).data('likes-count')
      });
      authenticatedUser.bind('change', function() {
        if (authenticatedUser.get('username')) {
          likeModel.bind('loadModelCompleted', function() {
            likeModel.set('likeable', true);
          });
          likeModel.fetch();
        }
      });
      var likeView = new LikeView({
        el: this,
        model: likeModel
      });
      likeView.render();
    });

    authenticatedUser.fetch();
  });
});
<commit_msg>Applying necessary changes to public dashboard pages in order to render properly map previews<commit_after>var $ = require('jquery');
var cdb = require('cartodb.js');
var FavMapView = require('./fav_map_view');
var UserInfoView = require('./user_info_view');
var PaginationModel = require('../common/views/pagination/model');
var PaginationView = require('../common/views/pagination/view');
var UserSettingsView = require('../public_common/user_settings_view');
var UserTourView = require('../public_common/user_tour_view');
var UserIndustriesView = require('../public_common/user_industries_view');
var UserResourcesView = require('../public_common/user_resources_view');
var MapCardPreview = require('../common/views/mapcard_preview');
var LikeView = require('../common/views/likes/view');
var ScrollableHeader = require('../common/views/scrollable_header');

$(function() {
  cdb.init(function() {
    cdb.templates.namespace = 'cartodb/';
    cdb.config.set(window.config);
    cdb.config.set('url_prefix', window.base_url);

    var scrollableHeader = new ScrollableHeader({
      el: $('.js-Navmenu'),
      anchorPoint: 350
    });

    var userTourView = new UserTourView({
      el: $('.js-user-tour'),
    });

    var userIndustriesView = new UserIndustriesView({
      el: $('.js-user-industries'),
    });

    var userResourcesView = new UserResourcesView({
      el: $('.js-user-resources'),
    });

    $(document.body).bind('click', function() {
      cdb.god.trigger('closeDialogs');
    });

    var authenticatedUser = new cdb.open.AuthenticatedUser();
    authenticatedUser.bind('change', function() {
      if (authenticatedUser.get('username')) {
        var user = new cdb.admin.User(authenticatedUser.attributes);
        var userSettingsView = new UserSettingsView({
          el: $('.js-user-settings'),
          model: user
        });
        userSettingsView.render();

        var userDashboardUrl = user.viewUrl().dashboard();
        $('.js-user-info .UserAvatar-img').wrap($('<a>',{
          href: userDashboardUrl
        }));

        $('.js-login').hide();
        $('.js-learn').show();
      }
    });

    var favMapView = new FavMapView(window.favMapViewAttrs);
    favMapView.render();

    var userInfoView = new UserInfoView({
      el: $('.js-user-info')
    });
    userInfoView.render();

    var paginationView = new PaginationView({
      el: '.js-content-footer',
      model: new PaginationModel(window.paginationModelAttrs)
    });
    paginationView.render();

    $('.MapCard').each(function() {
      var visId = $(this).data('visId');
      if (visId) {
        var mapCardPreview = new MapCardPreview({
          el: $(this).find('.js-header'),
          height: 220,
          visId: $(this).data('visId'),
          username: $(this).data('visOwnerName'),
          mapsApiHost: cdb.config.getMapsApiHost()
        });
        mapCardPreview.load();
      }
    });

    $('.js-likes').each(function() {
      var likeModel = cdb.admin.Like.newByVisData({
        url: !cdb.config.get('url_prefix') ? $(this).attr('href') : '' ,
        likeable: false,
        show_count: $(this).data('show-count') || false,
        show_label: $(this).data('show-label') || false,
        vis_id: $(this).data('vis-id'),
        likes: $(this).data('likes-count')
      });
      authenticatedUser.bind('change', function() {
        if (authenticatedUser.get('username')) {
          likeModel.bind('loadModelCompleted', function() {
            likeModel.set('likeable', true);
          });
          likeModel.fetch();
        }
      });
      var likeView = new LikeView({
        el: this,
        model: likeModel
      });
      likeView.render();
    });

    authenticatedUser.fetch();
  });
});
<|endoftext|>


<commit_before><commit_msg>Delete marshaller.js<commit_after><|endoftext|>


<commit_before>import { runCallbacksAsync } from 'meteor/vulcan:core';
import escapeStringRegexp from 'escape-string-regexp';
import { Picker } from 'meteor/meteorhacks:picker';
import { Posts } from '../../modules/posts/index.js';

Picker.route('/out', ({ query}, req, res, next) => {
  if(query.url){ // for some reason, query.url doesn't need to be decoded
    /*
    If the URL passed to ?url= is in plain text, any hash fragment
    will get stripped out.
    So we search for any post whose URL contains the current URL to get a match
    even without the hash
    */

    try {

      // decode url just in case
      const decodedUrl = decodeURIComponent(query.url);

      const post = Posts.findOne({url: {$regex: escapeStringRegexp(decodedUrl)}}, {sort: {postedAt: -1, createdAt: -1}});

      if (post) {
        const ip = req.headers && req.headers['x-forwarded-for'] || req.connection.remoteAddress;

        runCallbacksAsync('posts.click.async', post, ip);

        res.writeHead(301, {'Location': query.url});
        res.end();
      } else {
        // don't redirect if we can't find a post for that link
        res.end(`Invalid URL: ${query.url}`);
      }
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log('// /out error');
      // eslint-disable-next-line no-console
      console.log(error);
      // eslint-disable-next-line no-console
      console.log(query);
    }
  } else {
    res.end("Please provide a URL");
  }
});
<commit_msg>get rid of unnecessary decodeURIComponent<commit_after>import { runCallbacksAsync } from 'meteor/vulcan:core';
import escapeStringRegexp from 'escape-string-regexp';
import { Picker } from 'meteor/meteorhacks:picker';
import { Posts } from '../../modules/posts/index.js';

Picker.route('/out', ({ query}, req, res, next) => {
  if(query.url){ // for some reason, query.url doesn't need to be decoded
    /*
    If the URL passed to ?url= is in plain text, any hash fragment
    will get stripped out.
    So we search for any post whose URL contains the current URL to get a match
    even without the hash
    */

    try {

      const post = Posts.findOne({url: {$regex: escapeStringRegexp(query.url)}}, {sort: {postedAt: -1, createdAt: -1}});

      if (post) {
        const ip = req.headers && req.headers['x-forwarded-for'] || req.connection.remoteAddress;

        runCallbacksAsync('posts.click.async', post, ip);

        res.writeHead(301, {'Location': query.url});
        res.end();
      } else {
        // don't redirect if we can't find a post for that link
        res.end(`Invalid URL: ${query.url}`);
      }
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log('// /out error');
      // eslint-disable-next-line no-console
      console.log(error);
      // eslint-disable-next-line no-console
      console.log(query);
    }
  } else {
    res.end("Please provide a URL");
  }
});
<|endoftext|>