<commit_before>var currentDate = new Date();
// Committee list DOM
var $cteList = $('.cte-list');
var $cteGetAlerts = $('.cte-get-alerts');
var $cteSignupBox = $('.cte-signup-box');
var $cteListItems = $('.cte-list .tab-pane.active .committee');
var $cteListSearchInput = $('.cte-list-search input');
var $cteListSearchResults = $('.cte-list-search-results');
var $cteListNavItem = $('.cte-list-nav a, .cte-list-nav-mobile option');
var $cteListUserFollowing = $('.cte-list-user-following ul');
var $cteListFollowCommittee = $('.cte-follow-committee');
var $noCteFollowedMsg = $('.no-committees-followed');
// Committee details DOM
var $cteDtlNavItem = $('.cte-dtl-meetings-nav a, .cte-dtl-meetings-nav-mobile option');
var $cteDtlNavMobileSelect = $('.cte-dtl-meetings-nav-mobile select');
var $cteDtlFilterSelect = $('.cte-dtl-meetings-filter select');
var $cteDtlListTables = $('.cte-dtl-meetings-list .table');
var $cteDtlReadMore = $('.read-more a');
var $cteDtlMtngsList = $('.cte-dtl-meetings-list');
var $cteDtlMtngsSearchInput = $('.cte-dtl-meetings-search input');
var $cteDtlMtngsSearchResults = $('.cte-dtl-meetings-search-results');
var showingSearchResult = false;
// General elements
var $cteTabNav = $('.cte-tab-nav');
var $cteTabNavItem = $('.cte-tab-nav a');
var $cteSelectTabNav = $('.cte-select-tab-nav');
// Lunr elements
var $lunrDict = $('.lunr-dict');
var $lunrDictItems = null;
// megaMenu
var $megamenu = $('.megamenu');

// Set up lunr index for filtering
var index = null;

// Committee list page methods and handlers
var clearSearchResult = function($list,$res,params) {
  var $resultsList = $res.find('.results-list');

  $res.find('.no-results')
    .hide();

  if(!!params && params.twoCol) {
    $resultsList.find('.left, .right')
    .empty();
  } else {
    $resultsList.empty();
  }

  $resultsList.hide();
  $list.show();
}

// Underscore debounce
var debounce = function(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

var renderSearchResults = function(results,$list,$res,params) {
  var resultsCount = results.length;
  var $noResults = $res.find('.no-results');
  var $resultsList = $res.find('.results-list');

  showingSearchResult = true;

  $list.hide();
  $noResults.hide();

  if(!!resultsCount) {
    $resultsList.show();

    if(!!params && params.sort) {
      results.sort(function(a,b) {
        return new Date($(b).find('.date').text()) - new Date($(a).find('.date').text());
      });
    }

    if(!!params && params.twoCol) {
      var $resultsListLeft = $resultsList.find('.left');
      var $resultsListRight = $resultsList.find('.right');

      $resultsListLeft.empty();
      $resultsListRight.empty();

      if(resultsCount > 20) {
        if(resultsCount < 40) {
          $resultsListLeft.append(results.slice(0,19));
          $resultsListRight.append(results.slice(20));
        } else {
          $resultsListLeft.append(results.slice(0,resultsCount / 2 - 1));
          $resultsListRight.append(results.slice(resultsCount / 2));
        }
      } else {
        $resultsListLeft.append(results);
      }
    } else {
      $resultsList.empty()
        .append(results);
    }
  } else {
    $resultsList.hide();
    $noResults.show();
  }
};

var filterMeetings = function($target) {
  var filter = $target.attr('data-filter');
  var $table = $('#m-' + filter);

  $cteDtlListTables.hide();
  $table.fadeIn({ duration: 250, easing: 'linear' });

  return filter;
}

var searchIndex = debounce(function(query,$list,$res,params) {
  var results = null;

  if(!query.length)  {
    clearSearchResult($list,$res,params);
    return;
  } else {
    results = index.search(query).map(function(result) {
      return $lunrDictItems.filter(function(i,item) {
        return $(item).attr('data-id') == result.ref;
      })[0];
    });

    renderSearchResults(results,$list,$res,params);
  }
}, 200);

var indexItems = function() {
  var isCteDtlMeetings = $lunrDict.hasClass('cte-dtl-meetings-list');

  $lunrDictItems = $('.lunr-dict .item:not(.exclude), .lunr-dict .active .item:not(.exclude)').clone();

  index = lunr(function() {
    var self = this;

    self.field('name');

    // On the committee detail page, we also have the option to search meetings
    // by date
    if(isCteDtlMeetings) {
      self.field('date');
    }

    self.ref('id');
  });

  $lunrDictItems.each(function(i,item) {
    var $item = $(item);
    var indexItem = {
      id: $item.attr('data-id')
    };

    // Here we take lunr's index fields and add them as properties to each item.
    // We expect an item to have child elements that have class names that
    // match these fields.
    index._fields.forEach(function(field) {
      var name = field.name;

      indexItem[name] = $item.find('.' + name).text();
    });

    index.add(indexItem);
  });
}

/**
 * Event handlers
 */

 // For pairing tab navs with selects
 $cteTabNavItem.on('click', function(e) {
   e.preventDefault();
   $(this).tab('show');

   $cteSelectTabNav.val($(e.target).attr('href'));
 });

 $cteSelectTabNav.on('change', function(e) {
   e.preventDefault();

   var $selected = $('option:selected',this);

   $selected.tab('show');
   $cteTabNav.find('li')
     .removeClass('active')
     .has('[href="' + $selected.attr('data-target') + '"]')
     .closest('li')
     .addClass('active');
 });

 // Committee list page
$cteListNavItem.on('click', function(e) {
  e.preventDefault();
  $cteListItems = $('.cte-list .tab-pane.active .committee');

  indexItems();
  $cteListSearchInput.val('');

  if(showingSearchResult) clearSearchResult($cteList,$cteListSearchResults,{ twoCol: true });
});

$cteListSearchInput.on('keyup', function(e) {
  searchIndex($(e.target).val(), $cteList, $cteListSearchResults, { twoCol: true });
});

function insertIntoDOMList($list,$item,$container,name,nameTag) {
  if(!!$list.length) {
    $list.each(function(i) {
      var thisName = $(this).find(nameTag).html();
      var nextName = $($list[i + 1]).find(nameTag).html();

      if(name <= thisName) {
        $item.insertBefore($list[i]);
        return false;
      } else if((thisName < name && nextName >= name) || i == $list.length - 1) {
        $item.insertAfter($list[i]);
        return false;
      }
    });
  } else {
    $container.append($item);
  }
}

function mmUpdate() {
  $.get('/user/megamenu/', function(result) {
    $megamenu.empty().html(result);
  }, 'html');
}

$cteSignupBox.on('change','.cte-follow-committee input[type=checkbox]', function(e) {
  var $target = $(e.target);
  var $form = $target.closest('form');
  var data = $form.serialize();
  var url = $form.attr('action').split('/');
  var actionUrl = url.join('/');
  var id = url[url.length - 1];
  var isFollowing = url[2] == 'unfollow';

  if(isFollowing) {
    $('.mm-committees-list [data-id=' + id + '][data-follow-list="true"]').remove();

    $form.attr('action','/user/follow/committee/' + id)
      .find('input[type=checkbox]')
      .prop('checked', false);

    $cteGetAlerts.find('input[type=checkbox]')
      .prop('checked', false);
  } else {
    var name = $('.committee-name').html();
    var isPremium = $('.premium').length;

    $form.attr('action','/user/unfollow/committee/' + id)
      .find('input[type=checkbox]')
      .prop('checked', true);

      $cteGetAlerts.find('input[type=checkbox]')
        .prop('checked', true);
  }

  $.post(actionUrl, data, mmUpdate);
});

$cteList.on('change', '.cte-follow-committee input[type=checkbox]', function(e) {
    var $target = $(e.target);
    var $targetItem = $(e.target).closest('li');
    var id = $targetItem.attr('data-id');
    var $listItem = $('.cte-items [data-id=' + id + ']');
    var $cteListUserFollowingItems = $cteListUserFollowing.find('li');
    var $listItemForm = $listItem.find('form');
    var $followedItem = $('[data-id=' + id + '][data-follow-list="true"]');
    var data = $listItemForm.serialize();
    var actionUrl = $targetItem.find('form').attr('action');

    if(!!$targetItem.attr('data-following')) {
      $followedItem.remove();
      $listItem.removeAttr('data-following');
      $listItemForm.attr('action','/user/follow/committee/' + id)
        .find('input[type=checkbox]')
        .prop('checked',false);
    } else {
      // Attach to megamenu
      var name = $listItem.find('.name').html();
      var isPremium = $listItem.find('.premium').length;

      $listItem.attr('data-following','true');
      $listItemForm.attr('action','/user/unfollow/committee/' + id);

      insertIntoDOMList($cteListUserFollowingItems,$listItem.clone().attr('data-follow-list','true'),$cteListUserFollowing,name,'a');
    }

    if($cteListUserFollowing.find('li').length) {
      $noCteFollowedMsg.hide();
    } else {
      $noCteFollowedMsg.show();
    }

    $.post(actionUrl, data, mmUpdate);
});

// Committee detail page handlers
$cteDtlNavItem.on('click', indexItems);

$cteDtlFilterSelect.on('change', function(e) {
  filterMeetings($('option:selected',this));
  $cteDtlMtngsSearchInput.val('');

  clearSearchResult($cteDtlMtngsList,$cteDtlMtngsSearchResults);
  $cteDtlMtngsList.show();
});

$cteDtlFilterSelect.on('focus', function() {
  this.selectedIndex = -1;
});

$cteDtlFilterSelect.on('blur', function() {
  if(this.selectedIndex === -1) {
    this.selectedIndex = 0;
  }
});

// Committee detail meeting list filter
$cteDtlMtngsSearchInput.on('keyup', function(e) {
  searchIndex($(e.target).val(),$cteDtlMtngsList,$cteDtlMtngsSearchResults, { sort: true });
});

// Generate initial index
indexItems();
<commit_msg>Listen for change on cteList and cteListSearchResults<commit_after>var currentDate = new Date();
// Committee list DOM
var $cteList = $('.cte-list');
var $cteGetAlerts = $('.cte-get-alerts');
var $cteSignupBox = $('.cte-signup-box');
var $cteListItems = $('.cte-list .tab-pane.active .committee');
var $cteListSearchInput = $('.cte-list-search input');
var $cteListSearchResults = $('.cte-list-search-results');
var $cteListNavItem = $('.cte-list-nav a, .cte-list-nav-mobile option');
var $cteListUserFollowing = $('.cte-list-user-following ul');
var $cteListFollowCommittee = $('.cte-follow-committee');
var $noCteFollowedMsg = $('.no-committees-followed');
// Committee details DOM
var $cteDtlNavItem = $('.cte-dtl-meetings-nav a, .cte-dtl-meetings-nav-mobile option');
var $cteDtlNavMobileSelect = $('.cte-dtl-meetings-nav-mobile select');
var $cteDtlFilterSelect = $('.cte-dtl-meetings-filter select');
var $cteDtlListTables = $('.cte-dtl-meetings-list .table');
var $cteDtlReadMore = $('.read-more a');
var $cteDtlMtngsList = $('.cte-dtl-meetings-list');
var $cteDtlMtngsSearchInput = $('.cte-dtl-meetings-search input');
var $cteDtlMtngsSearchResults = $('.cte-dtl-meetings-search-results');
var showingSearchResult = false;
// General elements
var $cteTabNav = $('.cte-tab-nav');
var $cteTabNavItem = $('.cte-tab-nav a');
var $cteSelectTabNav = $('.cte-select-tab-nav');
// Lunr elements
var $lunrDict = $('.lunr-dict');
var $lunrDictItems = null;
// megaMenu
var $megamenu = $('.megamenu');

// Set up lunr index for filtering
var index = null;

// Committee list page methods and handlers
var clearSearchResult = function($list,$res,params) {
  var $resultsList = $res.find('.results-list');

  $res.find('.no-results')
    .hide();

  if(!!params && params.twoCol) {
    $resultsList.find('.left, .right')
    .empty();
  } else {
    $resultsList.empty();
  }

  $resultsList.hide();
  $list.show();
}

// Underscore debounce
var debounce = function(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

var renderSearchResults = function(results,$list,$res,params) {
  var resultsCount = results.length;
  var $noResults = $res.find('.no-results');
  var $resultsList = $res.find('.results-list');

  showingSearchResult = true;

  $list.hide();
  $noResults.hide();

  if(!!resultsCount) {
    $resultsList.show();

    if(!!params && params.sort) {
      results.sort(function(a,b) {
        return new Date($(b).find('.date').text()) - new Date($(a).find('.date').text());
      });
    }

    if(!!params && params.twoCol) {
      var $resultsListLeft = $resultsList.find('.left');
      var $resultsListRight = $resultsList.find('.right');

      $resultsListLeft.empty();
      $resultsListRight.empty();

      if(resultsCount > 20) {
        if(resultsCount < 40) {
          $resultsListLeft.append(results.slice(0,19));
          $resultsListRight.append(results.slice(20));
        } else {
          $resultsListLeft.append(results.slice(0,resultsCount / 2 - 1));
          $resultsListRight.append(results.slice(resultsCount / 2));
        }
      } else {
        $resultsListLeft.append(results);
      }
    } else {
      $resultsList.empty()
        .append(results);
    }
  } else {
    $resultsList.hide();
    $noResults.show();
  }
};

var filterMeetings = function($target) {
  var filter = $target.attr('data-filter');
  var $table = $('#m-' + filter);

  $cteDtlListTables.hide();
  $table.fadeIn({ duration: 250, easing: 'linear' });

  return filter;
}

var searchIndex = debounce(function(query,$list,$res,params) {
  var results = null;

  if(!query.length)  {
    clearSearchResult($list,$res,params);
    return;
  } else {
    results = index.search(query).map(function(result) {
      return $lunrDictItems.filter(function(i,item) {
        return $(item).attr('data-id') == result.ref;
      })[0];
    });

    renderSearchResults(results,$list,$res,params);
  }
}, 200);

var indexItems = function() {
  var isCteDtlMeetings = $lunrDict.hasClass('cte-dtl-meetings-list');

  $lunrDictItems = $('.lunr-dict .item:not(.exclude), .lunr-dict .active .item:not(.exclude)').clone();

  index = lunr(function() {
    var self = this;

    self.field('name');

    // On the committee detail page, we also have the option to search meetings
    // by date
    if(isCteDtlMeetings) {
      self.field('date');
    }

    self.ref('id');
  });

  $lunrDictItems.each(function(i,item) {
    var $item = $(item);
    var indexItem = {
      id: $item.attr('data-id')
    };

    // Here we take lunr's index fields and add them as properties to each item.
    // We expect an item to have child elements that have class names that
    // match these fields.
    index._fields.forEach(function(field) {
      var name = field.name;

      indexItem[name] = $item.find('.' + name).text();
    });

    index.add(indexItem);
  });
}

var committeeFollowChange = function(e) {
    var $target = $(e.target);
    var $targetItem = $target.closest('li');
    var id = $targetItem.attr('data-id');
    var $listItem = $('.cte-items [data-id=' + id + ']');
    var $cteListUserFollowingItems = $cteListUserFollowing.find('li');
    var $listItemForm = $listItem.find('form');
    var $followedItem = $('[data-id=' + id + '][data-follow-list="true"]');
    var data = $listItemForm.serialize();
    var actionUrl = $targetItem.find('form').attr('action');

    if(!!$targetItem.attr('data-following')) {
      $followedItem.remove();
      $listItem.removeAttr('data-following');
      $listItemForm.attr('action','/user/follow/committee/' + id)
        .find('input[type=checkbox]')
        .prop('checked', false);
    } else {
      // Attach to megamenu
      var name = $listItem.find('.name').html();
      var isPremium = $listItem.find('.premium').length;

      $listItem.attr('data-following','true');
      $listItemForm.attr('action','/user/unfollow/committee/' + id)
        .find('input[type=checkbox]')
        .prop('checked', true);

      insertIntoDOMList($cteListUserFollowingItems,$listItem.clone().attr('data-follow-list', 'true'), $cteListUserFollowing, name, 'a');
    }

    if($cteListUserFollowing.find('li').length) {
      $noCteFollowedMsg.hide();
    } else {
      $noCteFollowedMsg.show();
    }

    $.post(actionUrl, data, mmUpdate);
}

/**
 * Event handlers
 */

 // For pairing tab navs with selects
 $cteTabNavItem.on('click', function(e) {
   e.preventDefault();
   $(this).tab('show');

   $cteSelectTabNav.val($(e.target).attr('href'));
 });

 $cteSelectTabNav.on('change', function(e) {
   e.preventDefault();

   var $selected = $('option:selected',this);

   $selected.tab('show');
   $cteTabNav.find('li')
     .removeClass('active')
     .has('[href="' + $selected.attr('data-target') + '"]')
     .closest('li')
     .addClass('active');
 });

 // Committee list page
$cteListNavItem.on('click', function(e) {
  e.preventDefault();
  $cteListItems = $('.cte-list .tab-pane.active .committee');

  indexItems();
  $cteListSearchInput.val('');

  if(showingSearchResult) clearSearchResult($cteList,$cteListSearchResults,{ twoCol: true });
});

$cteListSearchInput.on('keyup', function(e) {
  searchIndex($(e.target).val(), $cteList, $cteListSearchResults, { twoCol: true });
});

function insertIntoDOMList($list,$item,$container,name,nameTag) {
  if(!!$list.length) {
    $list.each(function(i) {
      var thisName = $(this).find(nameTag).html();
      var nextName = $($list[i + 1]).find(nameTag).html();

      if(name <= thisName) {
        $item.insertBefore($list[i]);
        return false;
      } else if((thisName < name && nextName >= name) || i == $list.length - 1) {
        $item.insertAfter($list[i]);
        return false;
      }
    });
  } else {
    $container.append($item);
  }
}

function mmUpdate() {
  $.get('/user/megamenu/', function(result) {
    $megamenu.empty().html(result);
  }, 'html');
}

$cteSignupBox.on('change','.cte-follow-committee input[type=checkbox]', function(e) {
  var $target = $(e.target);
  var $form = $target.closest('form');
  var data = $form.serialize();
  var url = $form.attr('action').split('/');
  var actionUrl = url.join('/');
  var id = url[url.length - 1];
  var isFollowing = url[2] == 'unfollow';

  if(isFollowing) {
    $('.mm-committees-list [data-id=' + id + '][data-follow-list="true"]').remove();

    $form.attr('action','/user/follow/committee/' + id)
      .find('input[type=checkbox]')
      .prop('checked', false);

    $cteGetAlerts.find('input[type=checkbox]')
      .prop('checked', false);
  } else {
    var name = $('.committee-name').html();
    var isPremium = $('.premium').length;

    $form.attr('action','/user/unfollow/committee/' + id)
      .find('input[type=checkbox]')
      .prop('checked', true);

      $cteGetAlerts.find('input[type=checkbox]')
        .prop('checked', true);
  }

  $.post(actionUrl, data, mmUpdate);
});

$cteList.on('change', '.cte-follow-committee input[type=checkbox]', committeeFollowChange);
$cteListSearchResults.on('change', '.cte-follow-committee input[type=checkbox]', committeeFollowChange);

// Committee detail page handlers
$cteDtlNavItem.on('click', indexItems);

$cteDtlFilterSelect.on('change', function(e) {
  filterMeetings($('option:selected',this));
  $cteDtlMtngsSearchInput.val('');

  clearSearchResult($cteDtlMtngsList,$cteDtlMtngsSearchResults);
  $cteDtlMtngsList.show();
});

$cteDtlFilterSelect.on('focus', function() {
  this.selectedIndex = -1;
});

$cteDtlFilterSelect.on('blur', function() {
  if(this.selectedIndex === -1) {
    this.selectedIndex = 0;
  }
});

// Committee detail meeting list filter
$cteDtlMtngsSearchInput.on('keyup', function(e) {
  searchIndex($(e.target).val(),$cteDtlMtngsList,$cteDtlMtngsSearchResults, { sort: true });
});

// Generate initial index
indexItems();
<|endoftext|>


<commit_before>

function after_execution(url){
    $.getJSON(url, {}, function(data) {});
};

function update_action(url){
              var toreplay = $(this).closest('.dace-action').data('toreplay');
              var target = $(this).closest('.dace-action').data('target')+'-modal';
              if (Boolean(toreplay)){$(target).modal('show'); return false}
              var url = $(this).closest('.dace-action').data('updateurl');
              $.getJSON(url,{tomerge:'True', coordinates:'main'}, function(data) {
                 var action_body = data['body'];
                 if (action_body){
                     $($(target).find('.modal-body')).html(action_body);
                     $(target).modal('show');
                     try {
                          deform.processCallbacks();
                      }
                     catch(err) {};
                  }else{
                     location.reload();
                     return false
                  }
              });
              return false;
};

$(function() {

$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
    // Avoid following the href location when clicking
    event.preventDefault();
    // Avoid having the menu to close when clicking
    event.stopPropagation();
    // If a menu is already open we close it
    //$('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
    // opening the one you clicked on
    $(this).parent().addClass('open');

    var menu = $(this).parent().find("ul");
    var menupos = menu.offset();

    if ((menupos.left + menu.width()) + 30 > $(window).width()) {
        var newpos = - menu.width();
    } else {
        var newpos = $(this).parent().width();
    }
    menu.css({ left:newpos });

});

    $(document).on('click', '.pager li a', function() {
          var target = $(this).closest('.pager').data('target');
          var url = $(this).attr('href');
          $.get(url, {}, function(data) {
                $(target).html($(data).find(target).html());
                $("html, body").animate({ scrollTop: $(target)[0].getBoundingClientRect().top }, "slow");
          });
          return false;
    });

    $(document).on('click', '.dace-action', update_action);

    $('.current-iteration').addClass('success');

    $('.toggle').on('click', function() {
       $($(this).data('target')).toggle().toggleClass('out').toggleClass('in');
      });

    $($('.toggle').data('target')+'.out').hide();

});
<commit_msg>use $(target).offset().top instead of $(target)[0].getBoundingClientRect().top<commit_after>

function after_execution(url){
    $.getJSON(url, {}, function(data) {});
};

function update_action(url){
              var toreplay = $(this).closest('.dace-action').data('toreplay');
              var target = $(this).closest('.dace-action').data('target')+'-modal';
              if (Boolean(toreplay)){$(target).modal('show'); return false}
              var url = $(this).closest('.dace-action').data('updateurl');
              $.getJSON(url,{tomerge:'True', coordinates:'main'}, function(data) {
                 var action_body = data['body'];
                 if (action_body){
                     $($(target).find('.modal-body')).html(action_body);
                     $(target).modal('show');
                     try {
                          deform.processCallbacks();
                      }
                     catch(err) {};
                  }else{
                     location.reload();
                     return false
                  }
              });
              return false;
};

$(function() {

$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
    // Avoid following the href location when clicking
    event.preventDefault();
    // Avoid having the menu to close when clicking
    event.stopPropagation();
    // If a menu is already open we close it
    //$('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
    // opening the one you clicked on
    $(this).parent().addClass('open');

    var menu = $(this).parent().find("ul");
    var menupos = menu.offset();

    if ((menupos.left + menu.width()) + 30 > $(window).width()) {
        var newpos = - menu.width();
    } else {
        var newpos = $(this).parent().width();
    }
    menu.css({ left:newpos });

});

    $(document).on('click', '.pager li a', function() {
          var target = $(this).closest('.pager').data('target');
          var url = $(this).attr('href');
          $.get(url, {}, function(data) {
                $(target).html($(data).find(target).html());
                $("html, body").animate({ scrollTop: $(target).offset().top }, "slow");
          });
          return false;
    });

    $(document).on('click', '.dace-action', update_action);

    $('.current-iteration').addClass('success');

    $('.toggle').on('click', function() {
       $($(this).data('target')).toggle().toggleClass('out').toggleClass('in');
      });

    $($('.toggle').data('target')+'.out').hide();

});
<|endoftext|>


<commit_before>$(function() {
  var drawScores = $.getJSON("endpoints/scores", function(json) {
    data = make_score_data(json)
    showPie("#score", data);
  });
  var drawAlive = $.getJSON("endpoints/alive", function(json) {
    data = make_alive_data(json)
    showPie("#alive", data);
  });
  var drawSd = $.getJSON("endpoints/service_descriptions", function(json) {
    data = make_sd_data(json)
    showPie("#sd", data);
  });

  setTimeout(function(){ drawScores.abort(); }, 10000);
  setTimeout(function(){ drawAlive.abort(); }, 10000);
  setTimeout(function(){ drawSd.abort(); }, 10000);

  var drawScoreStatistics = $.getJSON("endpoints/score_statistics", function(json) {
    var labels = json['labels'];
    var datasets = json['datasets'];
    data = make_score_statistics_data(labels, datasets)
    showLine("#score_statistics", data, make_scale_options(100));
  });
  var drawAliveStatistics = $.getJSON("endpoints/alive_statistics", function(json) {
    var labels = json['labels'];
    var datasets = json['datasets'];
    data = make_alive_statistics_data(labels, datasets)
    var max = select_max_from_data(datasets[0]['data'])
    showLine("#alive_statistics", data, make_scale_options(max));
  });
  var drawSdStatistics = $.getJSON("endpoints/service_description_statistics", function(json) {
    var labels = json['labels'];
    var datasets = json['datasets'];
    data = make_sd_statistics_data(labels, datasets)
    var max = select_max_from_data(datasets[0]['data'])
    showLine("#sd_statistics", data, make_scale_options(max));
  });

  setTimeout(function(){ drawScoreStatistics.abort(); }, 10000);
  setTimeout(function(){ drawAliveStatistics.abort(); }, 10000);
  setTimeout(function(){ drawSdStatistics.abort(); }, 10000);
});

function make_score_data(count) {
  return {
    labels: ['Rank A', 'Rank B', 'Rank C', 'Rank D', 'Rank E'],
    datasets: [
      {
        data: [count[5], count[4], count[3], count[2], count[1]],
        backgroundColor: ['#1D2088', '#00A0E9', '#009944', '#FFF100', '#E60012'],
        hoverBackgroundColor: ['#6356A3', '#00B9EF', '#03EB37', '#FFF462', '#FF5A5E']
      }
    ],
    options: {
      legend: false
    }
  };
}
function make_alive_data(count) {
  return {
    labels: ['Alive', 'Dead'],
    datasets: [
      {
        data: [
          count['alive'],
          count['dead']
        ],
        backgroundColor: [
          '#00A0E9',
          '#E60012'
        ],
        hoverBackgroundColor: [
          '#00B9EF',
          '#FF5A5E'
        ]
      }
    ]
  };
}
function make_sd_data(count) {
  return {
    labels: ['Have', 'Do not have'],
    datasets: [
      {
        data: [
          count['true'],
          count['false']
        ],
        backgroundColor: [
          '#00A0E9',
          '#E60012'
        ],
        hoverBackgroundColor: [
          '#00B9EF',
          '#FF5A5E'
        ]
      }
    ]
  };
}
function make_score_statistics_data(labels, datasets) {
  return {
    labels: labels,
    datasets: [
      {
        label: datasets[0]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(0,160,233,0.2)',
        borderColor: 'rgba(0,160,233,1)',
        pointBorderColor: 'rgba(0,160,233,1)',
        pointBackgroundColor: '#fff',
        data: datasets[0]['data']
      },
      {
        label: datasets[1]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgba(255, 99, 132,1)',
        pointBorderColor: 'rgba(255, 99, 132,1)',
        pointBackgroundColor: '#fff',
        data: datasets[1]['data']
      }
    ]
  }
}
function make_alive_statistics_data(labels, datasets) {
  return {
    labels: labels,
    datasets: [
      {
        label: datasets[0]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(0,160,233,0.2)',
        borderColor: 'rgba(0,160,233,1)',
        pointBorderColor: 'rgba(0,160,233,1)',
        pointBackgroundColor: '#fff',
        data: datasets[0]['data']
      }
    ]
  }
}

function make_sd_statistics_data(labels, datasets) {
  return {
    labels: labels,
    datasets: [
      {
        label: datasets[0]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(0,160,233,0.2)',
        borderColor: 'rgba(0,160,233,1)',
        pointBorderColor: 'rgba(0,160,233,1)',
        pointBackgroundColor: '#fff',
        data: datasets[0]['data']
      }
    ]
  }
}

function make_scale_options(max) {
  return {
    scales: {
      yAxes: [{
        ticks: {
          max: max += 10,
          min: 0
        }
      }]
    }
  }
}

function select_max_from_data(data) {
  var max = Math.max(...data)
  return (max > 100) ? max : 100
}

function showPie(id, data) {
  new Chart($(id), {
    type: 'pie',
    data: data,
    options: {
      animation: {
        animateScale: true
      }
    }
  });
}

function showLine(context, data, options) {
  var lineChart = new Chart($(context), {
    type: 'line',
    data: data,
    options: options
  });
  $(context).on("click", function(evt){
    var activePoints = lineChart.getElementsAtEvent(evt);
    if (activePoints.length == 0) {
      return
    }
    var datestring = data.labels[0];
    var clickedDate = new Date(datestring);
    var index = activePoints[0]['_index'];
    clickedDate.setDate(clickedDate.getDate() + index);
    var clickedDateFormat = clickedDate.getFullYear() + "-" + (clickedDate.getMonth() + 1) + "-" + clickedDate.getDate();
    location.href = "http://192.168.99.100:3000?date=" + clickedDateFormat;
  });

}
<commit_msg>arrage the formatt of date<commit_after>$(function() {
  var drawScores = $.getJSON("endpoints/scores", function(json) {
    data = make_score_data(json)
    showPie("#score", data);
  });
  var drawAlive = $.getJSON("endpoints/alive", function(json) {
    data = make_alive_data(json)
    showPie("#alive", data);
  });
  var drawSd = $.getJSON("endpoints/service_descriptions", function(json) {
    data = make_sd_data(json)
    showPie("#sd", data);
  });

  setTimeout(function(){ drawScores.abort(); }, 10000);
  setTimeout(function(){ drawAlive.abort(); }, 10000);
  setTimeout(function(){ drawSd.abort(); }, 10000);

  var drawScoreStatistics = $.getJSON("endpoints/score_statistics", function(json) {
    var labels = json['labels'];
    var datasets = json['datasets'];
    data = make_score_statistics_data(labels, datasets)
    showLine("#score_statistics", data, make_scale_options(100));
  });
  var drawAliveStatistics = $.getJSON("endpoints/alive_statistics", function(json) {
    var labels = json['labels'];
    var datasets = json['datasets'];
    data = make_alive_statistics_data(labels, datasets)
    var max = select_max_from_data(datasets[0]['data'])
    showLine("#alive_statistics", data, make_scale_options(max));
  });
  var drawSdStatistics = $.getJSON("endpoints/service_description_statistics", function(json) {
    var labels = json['labels'];
    var datasets = json['datasets'];
    data = make_sd_statistics_data(labels, datasets)
    var max = select_max_from_data(datasets[0]['data'])
    showLine("#sd_statistics", data, make_scale_options(max));
  });

  setTimeout(function(){ drawScoreStatistics.abort(); }, 10000);
  setTimeout(function(){ drawAliveStatistics.abort(); }, 10000);
  setTimeout(function(){ drawSdStatistics.abort(); }, 10000);
});

function make_score_data(count) {
  return {
    labels: ['Rank A', 'Rank B', 'Rank C', 'Rank D', 'Rank E'],
    datasets: [
      {
        data: [count[5], count[4], count[3], count[2], count[1]],
        backgroundColor: ['#1D2088', '#00A0E9', '#009944', '#FFF100', '#E60012'],
        hoverBackgroundColor: ['#6356A3', '#00B9EF', '#03EB37', '#FFF462', '#FF5A5E']
      }
    ],
    options: {
      legend: false
    }
  };
}
function make_alive_data(count) {
  return {
    labels: ['Alive', 'Dead'],
    datasets: [
      {
        data: [
          count['alive'],
          count['dead']
        ],
        backgroundColor: [
          '#00A0E9',
          '#E60012'
        ],
        hoverBackgroundColor: [
          '#00B9EF',
          '#FF5A5E'
        ]
      }
    ]
  };
}
function make_sd_data(count) {
  return {
    labels: ['Have', 'Do not have'],
    datasets: [
      {
        data: [
          count['true'],
          count['false']
        ],
        backgroundColor: [
          '#00A0E9',
          '#E60012'
        ],
        hoverBackgroundColor: [
          '#00B9EF',
          '#FF5A5E'
        ]
      }
    ]
  };
}
function make_score_statistics_data(labels, datasets) {
  return {
    labels: labels,
    datasets: [
      {
        label: datasets[0]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(0,160,233,0.2)',
        borderColor: 'rgba(0,160,233,1)',
        pointBorderColor: 'rgba(0,160,233,1)',
        pointBackgroundColor: '#fff',
        data: datasets[0]['data']
      },
      {
        label: datasets[1]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgba(255, 99, 132,1)',
        pointBorderColor: 'rgba(255, 99, 132,1)',
        pointBackgroundColor: '#fff',
        data: datasets[1]['data']
      }
    ]
  }
}
function make_alive_statistics_data(labels, datasets) {
  return {
    labels: labels,
    datasets: [
      {
        label: datasets[0]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(0,160,233,0.2)',
        borderColor: 'rgba(0,160,233,1)',
        pointBorderColor: 'rgba(0,160,233,1)',
        pointBackgroundColor: '#fff',
        data: datasets[0]['data']
      }
    ]
  }
}

function make_sd_statistics_data(labels, datasets) {
  return {
    labels: labels,
    datasets: [
      {
        label: datasets[0]['label'],
        lineTension: 0,
        backgroundColor: 'rgba(0,160,233,0.2)',
        borderColor: 'rgba(0,160,233,1)',
        pointBorderColor: 'rgba(0,160,233,1)',
        pointBackgroundColor: '#fff',
        data: datasets[0]['data']
      }
    ]
  }
}

function make_scale_options(max) {
  return {
    scales: {
      yAxes: [{
        ticks: {
          max: max += 10,
          min: 0
        }
      }]
    }
  }
}

function select_max_from_data(data) {
  var max = Math.max(...data)
  return (max > 100) ? max : 100
}

function showPie(id, data) {
  new Chart($(id), {
    type: 'pie',
    data: data,
    options: {
      animation: {
        animateScale: true
      }
    }
  });
}

function showLine(context, data, options) {
  var lineChart = new Chart($(context), {
    type: 'line',
    data: data,
    options: options
  });
  $(context).on("click", function(evt){
    var activePoints = lineChart.getElementsAtEvent(evt);
    if (activePoints.length == 0) {
      return
    }
    var datestring = data.labels[0];
    var clickedDate = new Date(datestring);
    var index = activePoints[0]['_index'];
    clickedDate.setDate(clickedDate.getDate() + index);
    var clickedDateFormat = clickedDate.getFullYear() + "-" + ("0" + (clickedDate.getMonth() + 1)).slice(-2) + "-" + clickedDate.getDate();
    location.href = "http://192.168.99.100:3000?date=" + clickedDateFormat;
  });

}
<|endoftext|>


<commit_before>/**
* Template - search
*/
Template.search.rendered = function () {
  AutoCompletion.init("input#searchBox");
}

Template.search.events = {
  'keyup input#searchBox': function () {
    AutoCompletion.autocomplete({
      element: 'input#searchBox',       // DOM identifier for the element
      collection: Friends,              // MeteorJS collection object
      field: 'name',                    // Document field name to search for
      limit: 0,                         // Max number of elements to show
      sort: { name: 1 }});              // Sort object to filter results with
      //filter: { 'gender': 'female' }}); // Additional filtering
  }
}<commit_msg>Added debug logging in the example app<commit_after>/**
* Template - search
*/
Template.search.rendered = function () {
  AutoCompletion.enableLogging = true;
  AutoCompletion.init("input#searchBox");
}

Template.search.events = {
  'keyup input#searchBox': function () {
    AutoCompletion.autocomplete({
      element: 'input#searchBox',       // DOM identifier for the element
      collection: Friends,              // MeteorJS collection object
      field: 'name',                    // Document field name to search for
      limit: 0,                         // Max number of elements to show
      sort: { name: 1 }});              // Sort object to filter results with
      //filter: { 'gender': 'female' }}); // Additional filtering
  }
}<|endoftext|>


<commit_before>ace.define("ace/theme/monokai",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!0,t.cssClass="ace-monokai",t.cssText=".ace-monokai .ace_gutter {background: #2F3129;color: #8F908A}.ace-monokai .ace_print-margin {width: 1px;background: #555651}.ace-monokai {background-color: #272822;color: #F8F8F2}.ace-monokai .ace_cursor {color: #F8F8F0}.ace-monokai .ace_marker-layer .ace_selection {background: #49483E}.ace-monokai.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #272822;}.ace-monokai .ace_marker-layer .ace_step {background: rgb(102, 82, 0)}.ace-monokai .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #49483E}.ace-monokai .ace_marker-layer .ace_active-line {background: #202020}.ace-monokai .ace_gutter-active-line {background-color: #272727}.ace-monokai .ace_marker-layer .ace_selected-word {border: 1px solid #49483E}.ace-monokai .ace_invisible {color: #52524d}.ace-monokai .ace_entity.ace_name.ace_tag,.ace-monokai .ace_keyword,.ace-monokai .ace_meta.ace_tag,.ace-monokai .ace_storage {color: #F92672}.ace-monokai .ace_punctuation,.ace-monokai .ace_punctuation.ace_tag {color: #fff}.ace-monokai .ace_constant.ace_character,.ace-monokai .ace_constant.ace_language,.ace-monokai .ace_constant.ace_numeric,.ace-monokai .ace_constant.ace_other {color: #AE81FF}.ace-monokai .ace_invalid {color: #F8F8F0;background-color: #F92672}.ace-monokai .ace_invalid.ace_deprecated {color: #F8F8F0;background-color: #AE81FF}.ace-monokai .ace_support.ace_constant,.ace-monokai .ace_support.ace_function {color: #66D9EF}.ace-monokai .ace_fold {background-color: #A6E22E;border-color: #F8F8F2}.ace-monokai .ace_storage.ace_type,.ace-monokai .ace_support.ace_class,.ace-monokai .ace_support.ace_type {font-style: italic;color: #66D9EF}.ace-monokai .ace_entity.ace_name.ace_function,.ace-monokai .ace_entity.ace_other,.ace-monokai .ace_entity.ace_other.ace_attribute-name,.ace-monokai .ace_variable {color: #A6E22E}.ace-monokai .ace_variable.ace_parameter {font-style: italic;color: #FD971F}.ace-monokai .ace_string {color: #E6DB74}.ace-monokai .ace_comment {color: #75715E}.ace-monokai .ace_indent-guide {background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y}";var r=e("../lib/dom");r.importCssString(t.cssText,t.cssClass)})<commit_msg>Using light theme only<commit_after><|endoftext|>


<commit_before>
// fhq_echo_head

var last_pages = Array();

function echo_last_pages()
{
	if(last_pages.length > 10)
	{
		last_pages.splice(0, last_pages.length-10);
	}
	var content = "History Pages:

\n ";
	for(var i = last_pages.length - 1; i >= 0 ; i--)
	{
		var obj = last_pages[i];

		var map = {
			"quests_allow" : "Allow",
			"quests_completed" : "Completed",
			"quests_process" : "Process",
			"top100" : "Top 100",
			"user_info" : "Info",
			"feedback_add" : "Add feedback",
			"feedback_my" : "Feedback",
			"dr_zoyberg" : "Dr Zoyberg",
			"feedbacks" : "Feedbacks",
			"add_quest" : "Add Quest",
			"edit_quest" : "Edit Quest",
			"view_quest" : "View Quest"
		};

		var caption = map[obj.content_page];

		var content_page = "'" + obj.content_page + "'";
		var str = "" + JSON.stringify(obj.other_params);
		content += " " + obj.today.toLocaleTimeString() + ""
			+ " "
			+ caption + "

\n ";
	};
	document.getElementById("last_pages").innerHTML = content;
	// myArray.splice(0, 2)
};

function load_content_page(content_page, other_params, from_lp)
{
	if(other_params == 'undefined') other_params = {};
   if(from_lp == 'undefined') from_lp = false;

	if(
		content_page != 'take_quest' &&
		content_page != 'save_quest' &&
		content_page != 'pass_quest' &&
		content_page != 'delete_quest' &&
		content_page != 'remove_file' &&
		!from_lp
	)
		last_pages.push({ content_page: content_page, other_params: other_params, today : new Date() });

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	};
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			if(xmlhttp.responseText == "")
				document.getElementById("content_page").innerHTML = "content page don't found";
			else
			{
				echo_last_pages();
				document.getElementById("content_page").innerHTML=xmlhttp.responseText;
				document.getElementById("reload_content").onclick();
			}
		}
	}

	var url = "content_page.php?content_page=" + content_page;

	for(var key in other_params) {
		url = url + "&" + key + "=" + encodeURIComponent(other_params[key]);
	}

	// document.getElementById("debug_info").innerHTML=url;
	document.getElementById("content_page").innerHTML="";

	xmlhttp.open("GET", url ,true);
	xmlhttp.send();
};

function loadPage() {
	window.status = "Страница загружена";
};

function delete_quest() {

    if (!confirm("Are you sure want to delete quest?")) return false;
    else return true;
};

function delete_user() {

    if (!confirm("Are you sure want to delete user?")) return false;
    else return true;
};

function delete_file() {
    if (!confirm("Are you sure want to delete file?")) return false;
    else return true;
};

	// btn btn-large btn-primary
	// btn btn-small btn-info

function exit()
{
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
	 xmlhttp=new XMLHttpRequest();
  };
  xmlhttp.onreadystatechange=function()
  {
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		if(xmlhttp.responseText == "OK")
		{
			window.location.href = "index.php";
		}
	}
  }
  xmlhttp.open("GET","index.php?exit",true);
  xmlhttp.send();
};

// fhq_echo_menu

function dr_zoyberg()
{
  document.getElementById("content_page").innerHTML="";
};

function load_content_page_files(files, content_page, other_params) {

	if (window.XMLHttpRequest)
	{
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	};

	// alert(file);

    // Create form data
    var formData = new FormData();
    for(i = 0; i < files.length; i++)
		formData.append(files[i].name, files[i]);

	var url = "content_page.php?content_page=" + content_page;

	for(var key in other_params) {
		url = url + "&" + key + "=" + encodeURIComponent(other_params[key]);
	}
	// Open
	xmlhttp.open('POST', url, true);

    /*
    // Set headers
    xmlhttp.setRequestHeader("Cache-Control", "no-cache");
    xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
    xmlhttp.setRequestHeader("X-File-Name", file.name);
    xmlhttp.setRequestHeader("X-File-Size", file.size);
    xmlhttp.setRequestHeader("X-File-Type", "application/octet-stream");
	*/

	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			if(xmlhttp.responseText == "")
				document.getElementById("content_page").innerHTML = "content page don't found";
			else
			{
				echo_last_pages();
				document.getElementById("content_page").innerHTML=xmlhttp.responseText;
				document.getElementById("reload_content").onclick();
			}
		}
	}

	// Send
    xmlhttp.send(formData);
};

var myTimer;

function recalculate_score()
{
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	};
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var text = xmlhttp.responseText;

			document.getElementById("view_score").innerHTML=text;

			var value = parseInt(text,10);
			if(isNaN(value))
			{
				if(!myTimer) myTimer = setInterval(recalculate_score,1000);
			}
			else
			{
				clearInterval(myTimer);
				myTimer = undefined;
			}
		}
	}

	xmlhttp.open("GET", "content_page.php?content_page=recalculate_score",true);
	xmlhttp.send();
};
<commit_msg>fixed history pages<commit_after>
// fhq_echo_head

var last_pages = Array();

function echo_last_pages()
{
	if(last_pages.length > 10)
	{
		last_pages.splice(0, last_pages.length-10);
	}
	var content = "History Pages:

\n ";
	for(var i = last_pages.length - 1; i >= 0 ; i--)
	{
		var obj = last_pages[i];

		var map = {
			"quests_allow" : "Allow",
			"quests_completed" : "Completed",
			"quests_process" : "Process",
			"top100" : "Top 100",
			"user_info" : "Info",
			"feedback_add" : "Add feedback",
			"feedback_my" : "Feedback",
			"dr_zoyberg" : "Dr Zoyberg",
			"feedbacks" : "Feedbacks",
			"add_quest" : "Add Quest",
			"edit_quest" : "Edit Quest",
			"view_quest" : "View Quest"
		};

		var caption = map[obj.content_page];

		var content_page = "'" + obj.content_page + "'";
		var str = "" + JSON.stringify(obj.other_params);
		content += " " + obj.today.toLocaleTimeString() + ""
			+ " "
			+ caption + "

\n ";
	};
	document.getElementById("last_pages").innerHTML = content;
	// myArray.splice(0, 2)
};

function load_content_page(content_page, other_params, from_lp)
{
	if(other_params == 'undefined') other_params = {};
   if(from_lp == 'undefined') from_lp = false;

	if(
		content_page != 'take_quest' &&
		content_page != 'save_quest' &&
		content_page != 'pass_quest' &&
		content_page != 'delete_quest' &&
		content_page != 'remove_file' &&
		content_page != 'user_set_new_nick' &&
		content_page != 'user_set_new_role' &&
		content_page != 'send_mail_again' &&
		content_page != 'remove_user' &&
		!from_lp
	)
		last_pages.push({ content_page: content_page, other_params: other_params, today : new Date() });

	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	};
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			if(xmlhttp.responseText == "")
				document.getElementById("content_page").innerHTML = "content page don't found";
			else
			{
				echo_last_pages();
				document.getElementById("content_page").innerHTML=xmlhttp.responseText;
				document.getElementById("reload_content").onclick();
			}
		}
	}

	var url = "content_page.php?content_page=" + content_page;

	for(var key in other_params) {
		url = url + "&" + key + "=" + encodeURIComponent(other_params[key]);
	}

	// document.getElementById("debug_info").innerHTML=url;
	document.getElementById("content_page").innerHTML="";

	xmlhttp.open("GET", url ,true);
	xmlhttp.send();
};

function loadPage() {
	window.status = "Страница загружена";
};

function delete_quest() {

    if (!confirm("Are you sure want to delete quest?")) return false;
    else return true;
};

function delete_user() {

    if (!confirm("Are you sure want to delete user?")) return false;
    else return true;
};

function delete_file() {
    if (!confirm("Are you sure want to delete file?")) return false;
    else return true;
};

	// btn btn-large btn-primary
	// btn btn-small btn-info

function exit()
{
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
	 xmlhttp=new XMLHttpRequest();
  };
  xmlhttp.onreadystatechange=function()
  {
	if (xmlhttp.readyState==4 && xmlhttp.status==200)
	{
		if(xmlhttp.responseText == "OK")
		{
			window.location.href = "index.php";
		}
	}
  }
  xmlhttp.open("GET","index.php?exit",true);
  xmlhttp.send();
};

// fhq_echo_menu

function dr_zoyberg()
{
  document.getElementById("content_page").innerHTML="";
};

function load_content_page_files(files, content_page, other_params) {

	if (window.XMLHttpRequest)
	{
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	};

	// alert(file);

    // Create form data
    var formData = new FormData();
    for(i = 0; i < files.length; i++)
		formData.append(files[i].name, files[i]);

	var url = "content_page.php?content_page=" + content_page;

	for(var key in other_params) {
		url = url + "&" + key + "=" + encodeURIComponent(other_params[key]);
	}
	// Open
	xmlhttp.open('POST', url, true);

    /*
    // Set headers
    xmlhttp.setRequestHeader("Cache-Control", "no-cache");
    xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
    xmlhttp.setRequestHeader("X-File-Name", file.name);
    xmlhttp.setRequestHeader("X-File-Size", file.size);
    xmlhttp.setRequestHeader("X-File-Type", "application/octet-stream");
	*/

	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			if(xmlhttp.responseText == "")
				document.getElementById("content_page").innerHTML = "content page don't found";
			else
			{
				echo_last_pages();
				document.getElementById("content_page").innerHTML=xmlhttp.responseText;
				document.getElementById("reload_content").onclick();
			}
		}
	}

	// Send
    xmlhttp.send(formData);
};

var myTimer;

function recalculate_score()
{
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	};
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			var text = xmlhttp.responseText;

			document.getElementById("view_score").innerHTML=text;

			var value = parseInt(text,10);
			if(isNaN(value))
			{
				if(!myTimer) myTimer = setInterval(recalculate_score,1000);
			}
			else
			{
				clearInterval(myTimer);
				myTimer = undefined;
			}
		}
	}

	xmlhttp.open("GET", "content_page.php?content_page=recalculate_score",true);
	xmlhttp.send();
};
<|endoftext|>


<commit_before>'use strict';

/**
 * <%= componentName %> Directive.
 *
 * @ngdoc overview
 * @name  <%= moduleName %>.directive:<%= componentName %>
 * @description
 */

(function(){

  function <%= componentName %>Directive() {

    // Runs during compile
    return {
      // controller: function($scope, $element, $attrs, $transclude) {},
      // bindToController: true,
      // name: '',
      // priority: 1,
      // terminal: true,
      // scope: {}, // {} = isolate, true = child, false/undefined = no change
      // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
      restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
      //template: '',
      // replace: true,
      // transclude: true,
      // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
      // link: function($scope, iElm, iAttrs, controller) {}
    };

  }

  angular.module('<%= appName %>.<%= moduleName %>')
    .directive('<%= componentName %>',<%= componentName %>Directive);
})();
<commit_msg>feat(directive): Adds controllerAs. Close #23<commit_after>'use strict';

/**
 * <%= componentName %> Directive.
 *
 * @ngdoc overview
 * @name  <%= moduleName %>.directive:<%= componentName %>
 * @description
 */

(function(){

  function <%= componentName %>Directive() {

    // Runs during compile
    return {
      // controller: function($scope, $element, $attrs, $transclude) {},
      // controllerAs: '<%= componentName %>Controller',
      // bindToController: true,
      // name: '',
      // priority: 1,
      // terminal: true,
      // scope: {}, // {} = isolate, true = child, false/undefined = no change
      // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements
      restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
      //template: '',
      // replace: true,
      // transclude: true,
      // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})),
      // link: function($scope, iElm, iAttrs, controller) {}
    };

  }

  angular.module('<%= appName %>.<%= moduleName %>')
    .directive('<%= componentName %>',<%= componentName %>Directive);
})();
<|endoftext|>


<commit_before>import Ember from 'ember';
import { forEach } from 'ember-concurrency';
import { interval, dropIntermediateValues, keepFirstIntermediateValue } from 'ember-concurrency';

const Observable = window.Rx.Observable;

const {
  range,
  just,
} = Observable;

// 1 2 3 4 5 (150ms) 101 102 103 104 105
let rangeObservable = Observable.concat(
  range(1,5),
  range(101,5).delay(150)
);

// 1 (5ms) 2 3 (100ms) 4 5 6
let sporadicObservable = Observable.concat(
  just(1),
  just(2).delay(5),
  just(3),
  just(4).delay(100),
  just(5),
  just(6)
);

module('Unit: buffering');

function doBufferingTest(description, observable, bufferPolicyFn, expectations) {
  test(description, function(assert) {
    QUnit.stop();
    assert.expect(1);

    let last = expectations[expectations.length-1];

    let arr = [];
    Ember.run(() => {
      let obj = Ember.Object.create();
      forEach(observable, function * (v) {
        bufferPolicyFn();

        arr.push(v);
        yield interval(10);
        if (v === last) {
          Ember.run.later(() => {
            QUnit.start();
            assert.deepEqual(arr, expectations);
          }, 20);
        }
      }).attach(obj);
    });
  });
}

doBufferingTest("no buffering: ranges", rangeObservable, Ember.K, [1,2,3,4,5,101,102,103,104,105]);
doBufferingTest("no buffering: sporadic", sporadicObservable, Ember.K, [1,2,3,4,5,6]);

doBufferingTest("dropIntermediateValues: ranges", rangeObservable, dropIntermediateValues, [1,101]);
doBufferingTest("dropIntermediateValues: sporadic", sporadicObservable, dropIntermediateValues, [1,4]);

doBufferingTest("keepFirstIntermediateValue: ranges", rangeObservable, keepFirstIntermediateValue, [1, 2, 101, 102]);
doBufferingTest("keepFirstIntermediateValue: ranges", rangeObservable, dropIntermediateValues, [1,101]);

<commit_msg>fix keepFirstIntermediateValue test<commit_after>import Ember from 'ember';
import { forEach } from 'ember-concurrency';
import { interval, dropIntermediateValues, keepFirstIntermediateValue } from 'ember-concurrency';

const Observable = window.Rx.Observable;

const {
  range,
  just,
} = Observable;

// 1 2 3 4 5 (150ms) 101 102 103 104 105
let rangeObservable = Observable.concat(
  range(1,5),
  range(101,5).delay(150)
);

// 1 (2ms) 2 3 (100ms) 4 5 6
let sporadicObservable = Observable.concat(
  just(1),
  just(2).delay(5),
  just(3),
  just(4).delay(100),
  just(5),
  just(6)
);

module('Unit: buffering');

function doBufferingTest(description, observable, bufferPolicyFn, expectations) {
  test(description, function(assert) {
    QUnit.stop();
    assert.expect(1);

    let last = expectations[expectations.length-1];

    let arr = [];
    Ember.run(() => {
      let obj = Ember.Object.create();
      forEach(observable, function * (v) {
        bufferPolicyFn();

        arr.push(v);
        yield interval(10);
        if (v === last) {
          Ember.run.later(() => {
            QUnit.start();
            assert.deepEqual(arr, expectations);
          }, 20);
        }
      }).attach(obj);
    });
  });
}

doBufferingTest("no buffering: ranges", rangeObservable, Ember.K, [1,2,3,4,5,101,102,103,104,105]);
doBufferingTest("no buffering: sporadic", sporadicObservable, Ember.K, [1,2,3,4,5,6]);

doBufferingTest("dropIntermediateValues: ranges", rangeObservable, dropIntermediateValues, [1,101]);
doBufferingTest("dropIntermediateValues: sporadic", sporadicObservable, dropIntermediateValues, [1,4]);

doBufferingTest("keepFirstIntermediateValue: ranges", rangeObservable, keepFirstIntermediateValue, [1, 2, 101, 102]);
doBufferingTest("keepFirstIntermediateValue: ranges", rangeObservable, keepFirstIntermediateValue, [1,2,101,102]);

<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2019 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Tile = require('../Tile');
var IsInLayerBounds = require('./IsInLayerBounds');
var CalculateFacesAt = require('./CalculateFacesAt');

/**
 * Removes the tile at the given tile coordinates in the specified layer and updates the layer's
 * collision information.
 *
 * @function Phaser.Tilemaps.Components.RemoveTileAt
 * @private
 * @since 3.0.0
 *
 * @param {integer} tileX - The x coordinate.
 * @param {integer} tileY - The y coordinate.
 * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1.
 * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated.
 * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
 *
 * @return {Phaser.Tilemaps.Tile} The Tile object that was removed.
 */
var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, layer)
{
    if (replaceWithNull === undefined) { replaceWithNull = false; }
    if (recalculateFaces === undefined) { recalculateFaces = true; }
    if (!IsInLayerBounds(tileX, tileY, layer)) { return null; }

    var tile = layer.data[tileY][tileX] || null;
    if (tile === null)
    {
        return null;
    }
    else
    {
        layer.data[tileY][tileX] = replaceWithNull
            ? null
            : new Tile(layer, -1, tileX, tileY, tile.width, tile.height);
    }

    // Recalculate faces only if the removed tile was a colliding tile
    if (recalculateFaces && tile && tile.collides)
    {
        CalculateFacesAt(tileX, tileY, layer);
    }

    return tile;
};

module.exports = RemoveTileAt;
<commit_msg>Tidied up the formatting<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2019 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Tile = require('../Tile');
var IsInLayerBounds = require('./IsInLayerBounds');
var CalculateFacesAt = require('./CalculateFacesAt');

/**
 * Removes the tile at the given tile coordinates in the specified layer and updates the layer's
 * collision information.
 *
 * @function Phaser.Tilemaps.Components.RemoveTileAt
 * @private
 * @since 3.0.0
 *
 * @param {integer} tileX - The x coordinate.
 * @param {integer} tileY - The y coordinate.
 * @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified location with null instead of a Tile with an index of -1.
 * @param {boolean} [recalculateFaces=true] - `true` if the faces data should be recalculated.
 * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
 *
 * @return {Phaser.Tilemaps.Tile} The Tile object that was removed.
 */
var RemoveTileAt = function (tileX, tileY, replaceWithNull, recalculateFaces, layer)
{
    if (replaceWithNull === undefined) { replaceWithNull = false; }
    if (recalculateFaces === undefined) { recalculateFaces = true; }

    if (!IsInLayerBounds(tileX, tileY, layer))
    {
        return null;
    }

    var tile = layer.data[tileY][tileX];

    if (!tile)
    {
        return null;
    }
    else
    {
        layer.data[tileY][tileX] = (replaceWithNull) ? null : new Tile(layer, -1, tileX, tileY, tile.width, tile.height);
    }

    //  Recalculate faces only if the removed tile was a colliding tile
    if (recalculateFaces && tile && tile.collides)
    {
        CalculateFacesAt(tileX, tileY, layer);
    }

    return tile;
};

module.exports = RemoveTileAt;
<|endoftext|>


<commit_before>import { Posts } from '../../collection';

Template.postsForm.helpers({
  postsCollection () {
    return Posts;
  },
  updateInsert () {
    const instance = Template.instance();
    if (instance.data.postItem) {
      return "update";
    }
    else {
      return "insert";
    }
  }
});

Template.registerHelper('formatDate', function(date) {
  return moment(date).format('YYYY-MM-DD HH:mm');
});

Template.registerHelper('calculateFromDate', function(date) {
  // return moment(date).format('YYYY-MM-DD HH:mm');
  return moment(date).from(moment());
});

AutoForm.addHooks(['postsForm'],{
  onSuccess: function(operation, result, template){
    $('#postInsertModal').modal('hide');
  }
})
<commit_msg>modal hide implementation revised<commit_after>import { Posts } from '../../collection';

Template.postsForm.helpers({
  postsCollection () {
    return Posts;
  },
  updateInsert () {
    const instance = Template.instance();
    if (instance.data.postItem) {
      return "update";
    }
    else {
      return "insert";
    }
  }
});

Template.registerHelper('formatDate', function(date) {
  return moment(date).format('YYYY-MM-DD HH:mm');
});

Template.registerHelper('calculateFromDate', function(date) {
  // return moment(date).format('YYYY-MM-DD HH:mm');
  return moment(date).from(moment());
});

AutoForm.addHooks("postsForm",{
  onSuccess: function(){
    Modal.hide("postInsertModal");
  }
})
<|endoftext|>


<commit_before>exports.BattleMovedex = {
              "flameshot": {
		num: 2000,
		accuracy: 100,
		basePower: 40,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Flame Shot",
		isViable: true,
		name: "Flame Shot",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Fire"
	      },
	      "sapblast": {
		num: 2001,
		accuracy: 100,
		basePower: 40,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Sap Blast",
		isViable: true,
		name: "Sap Blast",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Grass"
	      },
	      "kineticforce": {
		num: 2002,
		accuracy: 100,
		basePower: 40,
		category: "Special",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Kinetic Force",
		isViable: true,
		name: "Kinetic Force",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Psychic"
	      },
	      "stonespine": {
		num: 2003,
		accuracy: 90,
		basePower: 55,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Stone Spine",
		isViable: true,
		name: "Stone Spine",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Rock"
	      },
	      "dracocrash": {
		num: 2004,
		accuracy: 90,
		basePower: 50,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Draco Crash",
		isViable: true,
		name: "Draco Crash",
		pp: 30,
		priority: 2,
		secondary: false,
		target: "normal",
		type: "Dragon"
	      },
	      "fairywind": {
		num: 584,
		accuracy: 100,
		basePower: 40,
		category: "Special",
		desc: "Deals damage to one adjacent target.",
		shortDesc: "No additional effect.",
		id: "fairywind",
		name: "Fairy Wind",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Fairy"
	      },
};
<commit_msg>Update moves.js<commit_after>exports.BattleMovedex = {
              "flameshot": {
		num: 2000,
		accuracy: 100,
		basePower: 40,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Flame Shot",
		isViable: true,
		name: "Flame Shot",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Fire"
	      },
	      "sapblast": {
		num: 2001,
		accuracy: 100,
		basePower: 40,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Sap Blast",
		isViable: true,
		name: "Sap Blast",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Grass"
	      },
	      "kineticforce": {
		num: 2002,
		accuracy: 100,
		basePower: 40,
		category: "Special",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Kinetic Force",
		isViable: true,
		name: "Kinetic Force",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Psychic"
	      },
	      "stonespine": {
		num: 2003,
		accuracy: 90,
		basePower: 55,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Stone Spine",
		isViable: true,
		name: "Stone Spine",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Rock"
	      },
	      "dracocrash": {
		num: 2004,
		accuracy: 90,
		basePower: 50,
		category: "Physical",
		desc: "Deals damage to one adjacent target. Priority +1.",
		shortDesc: "Usually goes first.",
		id: "Draco Crash",
		isViable: true,
		name: "Draco Crash",
		pp: 30,
		priority: 2,
		secondary: false,
		target: "normal",
		type: "Dragon"
	      },
	      "venomstrike": {
		num: 2005,
		accuracy: 100,
		basePower: 30,
		category: "Physical",
		desc: "Deals damage to one adjacent target.",
		shortDesc: "Usually goes first, 30% chance to badly poison the target.",
		id: "Venom Strike",
		name: "Venom Strike",
		pp: 30,
		priority: 1,
		isContact: true,
		secondary: {
			chance: 30,
			status: 'tox'
		},
		target: "normal",
		type: "Poison"
	      },
	      "fairywind": {
		num: 584,
		accuracy: 100,
		basePower: 40,
		category: "Special",
		desc: "Deals damage to one adjacent target.",
		shortDesc: "Usually goes first.",
		id: "fairywind",
		name: "Fairy Wind",
		pp: 30,
		priority: 1,
		secondary: false,
		target: "normal",
		type: "Fairy"
	      },
};
<|endoftext|>


<commit_before>(function () {
    "use strict";

    var cfg         = require('nconf'),
        fs          = require('fs'),
        node        = require('when/node'),
        readFile    = node.lift(fs.readFile),
        _           = require('lodash'),
        tpl;

    module.exports = {

        start: function () {

            var data = cfg.get('plugins:panda-google-analytics');

            if (!data || !data.ua || !data.domain) {
                this.status = 'W';
                this.messages.push({ msg: "Plugin could not start up properly due to missing configuration." });

                return when.reject();
            }

            return readFile(__dirname + '/code.txt')
                .then(function (src) {
                    tpl = _.template(src);
                });
        },

        stop: function () {
            tpl = null;
        },

        pageFooter: function () {
            return tpl(cfg.get('plugins:panda-google-analytics'));
        }
    };

    require('pkginfo')(module, ['version', 'name', 'code', 'description', 'configuration', 'author']);

}());<commit_msg>Missing module fix<commit_after>(function () {
    "use strict";

    var cfg         = require('nconf'),
        when        = require('when'),
        fs          = require('fs'),
        node        = require('when/node'),
        readFile    = node.lift(fs.readFile),
        _           = require('lodash'),
        tpl;

    module.exports = {

        start: function () {

            var data = cfg.get('plugins:panda-google-analytics');

            if (!data || !data.ua || !data.domain) {
                this.status = 'W';
                this.messages.push({ msg: "Plugin could not start up properly due to missing configuration." });

                return when.reject();
            }

            return readFile(__dirname + '/code.txt')
                .then(function (src) {
                    tpl = _.template(src);
                });
        },

        stop: function () {
            tpl = null;
        },

        pageFooter: function () {
            return tpl(cfg.get('plugins:panda-google-analytics'));
        }
    };

    require('pkginfo')(module, ['version', 'name', 'code', 'description', 'configuration', 'author']);

}());<|endoftext|>


<commit_before>/* Copyright (c) 2010, Sage Software, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Ext.namespace('Sage.Platform.Mobile.Controls');

(function() {
    Sage.Platform.Mobile.Controls.DecimalField = Ext.extend(Sage.Platform.Mobile.Controls.TextField, {
		inputType: 'number',
        precision: 2,
        setValue: function(val) {
            val = parseFloat(val, 10).toFixed(this.precision || 2);
            val = isNaN(val) ? '0.00' : val;
            Sage.Platform.Mobile.Controls.DecimalField.superclass.setValue.call(this, val);
        }
    });

    Sage.Platform.Mobile.Controls.FieldManager.register('decimal', Sage.Platform.Mobile.Controls.DecimalField);
})();<commit_msg>respects culture info for default decimal and no longer uses number type due to overriding validation logic by browsers<commit_after>/* Copyright (c) 2010, Sage Software, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Ext.namespace('Sage.Platform.Mobile.Controls');

(function() {
    Sage.Platform.Mobile.Controls.DecimalField = Ext.extend(Sage.Platform.Mobile.Controls.TextField, {
        precision: 2,
        setValue: function(val) {
            val = parseFloat(val, 10).toFixed(this.precision || Mobile.CultureInfo.numberFormat.currencyDecimalDigits);
            val = isNaN(val)
                ? String.format('0{0}00', Mobile.CultureInfo.numberFormat.currencyDecimalSeparator || '.')
                : val;
            Sage.Platform.Mobile.Controls.DecimalField.superclass.setValue.call(this, val);
        }
    });

    Sage.Platform.Mobile.Controls.FieldManager.register('decimal', Sage.Platform.Mobile.Controls.DecimalField);
})();<|endoftext|>


<commit_before>/*   Copyright 2017 Agneta Network Applications, LLC.
 *
 *   Source file: services/boot/sendgrid.js
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
var DataSource = require('loopback-datasource-juggler').DataSource;
var utils = require('loopback/lib/utils');
var _ = require('lodash');

module.exports = function(app) {

  var config = app.get('email');

  if (!config) {
    throw new Error('No Email config is present');
  }

  //--------------------------------------------------------------

  var subjectPrefix = _.get(config,'subject.prefix') || '';

  //--------------------------------------------------------------

  var dataSource;

  if (config.sendgrid) {
    dataSource = new DataSource('loopback-connector-sendgrid', {
      api_key: config.sendgrid.apiKey
    });
  }

  if (!dataSource) {
    throw new Error('Must have an email datasource');
  }

  app.loopback.Email.attachTo(dataSource);

  var emailSend = app.loopback.Email.send;

  app.loopback.Email.send = function(options, cb) {

    cb = cb || utils.createPromiseCallback();

    options.from = options.from || config.contacts.default;

    //-------
    if (!options.req) {
      return cb(new Error('Must have a request object to send email'));
    }
    options.language = app.getLng(options.req);

    //-------

    options.sender = options.from;
    if (_.isString(options.from)) {
      options.sender = {
        email: options.from
      };
    }
    options.from = options.sender.email;

    //-------

    options.receiver = options.to;
    if (_.isString(options.to)) {
      options.receiver = {
        email: options.to
      };
    }
    options.to = options.receiver.email;

    //-------

    _.extend(options.data, {
      info: config.info,
      language: options.language
    });

    ///////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////

    var template = config.templates[options.templateName];

    if (template) {
      template.render(options.data)
        .then(function(renderResult) {

          options.html = renderResult.html;
          options.text = renderResult.text;

          send();
        })
        .catch(cb);

    } else {
      send();
    }

    ///////////////////////////////////////////////////////////////

    function send() {

      options.text = options.text || config.text(options.html);

      //----------------------------------

      var subject = options.subject || template.data.subject;

      if (_.isObject(subject)) {
        subject = app.lng(subject, options.language);
      }

      options.subject = app.lng(subjectPrefix,options.language) + subject;

      //----------------------------------

      emailSend.call(app.loopback.Email, options)
        .catch(function(err) {
          console.error(err);
        });
    }

    return cb.promise;
  };

};
<commit_msg>Fix mail sending when rendering the ejs<commit_after>/*   Copyright 2017 Agneta Network Applications, LLC.
 *
 *   Source file: services/boot/sendgrid.js
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
var DataSource = require('loopback-datasource-juggler').DataSource;
var utils = require('loopback/lib/utils');
var _ = require('lodash');

module.exports = function(app) {

  var config = app.get('email');

  if (!config) {
    throw new Error('No Email config is present');
  }

  //--------------------------------------------------------------

  var subjectPrefix = _.get(config,'subject.prefix') || '';

  //--------------------------------------------------------------

  var dataSource;

  if (config.sendgrid) {
    dataSource = new DataSource('loopback-connector-sendgrid', {
      api_key: config.sendgrid.apiKey
    });
  }

  if (!dataSource) {
    throw new Error('Must have an email datasource');
  }

  app.loopback.Email.attachTo(dataSource);

  var emailSend = app.loopback.Email.send;

  app.loopback.Email.send = function(options, cb) {

    cb = cb || utils.createPromiseCallback();

    options.from = options.from || config.contacts.default;

    //-------
    if (!options.req) {
      return cb(new Error('Must have a request object to send email'));
    }
    options.language = app.getLng(options.req);

    //-------

    options.sender = options.from;
    if (_.isString(options.from)) {
      options.sender = {
        email: options.from
      };
    }
    options.from = options.sender.email;

    //-------

    options.receiver = options.to;
    if (_.isString(options.to)) {
      options.receiver = {
        email: options.to
      };
    }
    options.to = options.receiver.email;

    //-------

    _.extend(options.data, {
      info: config.info,
      language: options.language
    });

    ///////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////

    var template = config.templates[options.templateName];

    if (template) {
      var renderResult = template.render(options.data);

      options.html = renderResult.html;
      options.text = renderResult.text;

    }
    send();

    ///////////////////////////////////////////////////////////////

    function send() {

      options.text = options.text || config.text(options.html);

      //----------------------------------

      var subject = options.subject || template.data.subject;

      if (_.isObject(subject)) {
        subject = app.lng(subject, options.language);
      }

      options.subject = app.lng(subjectPrefix,options.language) + subject;

      //----------------------------------

      emailSend.call(app.loopback.Email, options)
        .catch(function(err) {
          console.error(err);
        });
    }

    return cb.promise;
  };

};
<|endoftext|>


<commit_before>var mdns = require('mdns'),
    EventEmitter = require('events').EventEmitter,
    serviceType = mdns.makeServiceType({name: 'http', protocol: 'tcp'});

module.exports.create = function (urn) {
  var instance = new EventEmitter(),
      urn      = urn ? urn : serviceType,
      browser  = urn ? mdns.createBrowser(urn) : mdns.browseThemAll(),
      started  = false;

  browser.on('serviceUp', function(msg) {
    // console.log(msg);

    var output = {
      id: msg.fullname,
      type: msg.type.toString(),
      location: msg.addresses ? msg.addresses[1] : '',
      server: msg.host,
      timestamp: new Date(),
      state: 'serviceup',
      protocol: 'MDNS'
    };

    if(output.id) {
      instance.emit('*', output);
    }
  });

  browser.on('serviceDown', function(msg) {
    // console.log(msg);

    var output = {
      id: msg.name + '.' + msg.type.toString() + msg.replyDomain,
      type: msg.type.toString(),
      location: msg.addresses ? msg.addresses[1] : '',
      server: msg.host,
      timestamp: new Date(),
      state: 'servicedown',
      protocol: 'MDNS'
    };

    if(output.id) {
      instance.emit('*', output);
    }
  });

  instance.start = function () {
    if(!started) {
     browser.start();
     started = true;
    }
  }

  return instance;
}<commit_msg>Allow browsing of all mDNS services if no type specified<commit_after>var mdns = require('mdns'),
    EventEmitter = require('events').EventEmitter,
    browsers = {};
    serviceType = mdns.makeServiceType({name: 'http', protocol: 'tcp'});

module.exports.create = function (service) {
  var instance = new EventEmitter(),
      browser,
      started;

  // If browser exists for service
  if ( service && browsers[service] ) {
    browsers[service].on('serviceUp', createServiceUpHandler(instance));
    browsers[service].on('serviceDown', createServiceDownHandler(instance));
  // If no browser for service
  } else if ( service ) {
    browsers[service] = createBrowserWithHandlers(service, instance);
  // Browse everything
  } else {
    service = '*';
    browsers[service] = mdns.browseThemAll();
    browsers[service].on('serviceUp', function (msg) {
      var service = mdns.makeServiceType(
        { name: msg.type.name, protocol: msg.type.protocol }
      );
      browsers[service] = createBrowserWithHandlers(service, instance);
      if (started) {
        browsers[service].start();
        browsers[service].started = true;
      }
    });
  }

  instance.start = function () {
    Object.keys(browsers).forEach(function (service) {
      if(!browsers[service].started) {
        browsers[service].start();
        browsers[service].started = true;
      }
    });
    started = true;
  }

  return instance;
}

function createBrowserWithHandlers(service, instance) {
    var type = mdns.makeServiceType(service);
    var browser = mdns.createBrowser(type);
    browser.on('serviceUp', createServiceUpHandler(instance));
    browser.on('serviceDown', createServiceDownHandler(instance));
    return browser;
}

function createServiceUpHandler(instance) {
  return function serviceUp(msg) {
    var output = {
      id: msg.fullname,
      type: msg.type.toString(),
      location: msg.addresses ? msg.addresses[1] : '',
      server: msg.host,
      timestamp: new Date(),
      state: 'serviceup',
      protocol: 'MDNS'
    };

    if(output.id) {
      instance.emit('*', output);
    }
  }
}

function createServiceDownHandler(instance) {
  return function serviceDown(msg) {
    var output = {
      id: msg.name + '.' + msg.type.toString() + msg.replyDomain,
      type: msg.type.toString(),
      location: msg.addresses ? msg.addresses[1] : '',
      server: msg.host,
      timestamp: new Date(),
      state: 'servicedown',
      protocol: 'MDNS'
    };

    if(output.id) {
      instance.emit('*', output);
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import { Simulate } from 'react-dom/test-utils'
import Editable from './Editable'

describe('Editable', () => {
  let parent = null
  let component = null
  let rendered = null

  function render(element) { ReactDOM.render(element, parent) }

  beforeEach(() => {
    parent = document.createElement('div')
    component = ReactDOM.render(<Editable />, parent)
    // eslint-disable-next-line react/no-find-dom-node
    rendered = () => ReactDOM.findDOMNode(component)
  })

  it('renders classes properly', () => {
    render(<Editable className="test-class" />)
    expect(rendered().classList.contains('editable')).toEqual(true)
    expect(rendered().classList.contains('test-class')).toEqual(true)

    render(<Editable readonly />)
    expect(rendered().classList.contains('readonly')).toEqual(true)
  })

  it('raises change events properly', () => {
    const onChange = jest.genMockFunction()

    render(<Editable value="first" onChange={onChange} />)
    component.handleToggleEditing()

    const editor = rendered().children[0]
    expect(editor.value).toEqual('first')
    Simulate.change(editor, { target: { value: 'second' } })
    Simulate.blur(editor)
    expect(onChange).toBeCalledWith('second', 'first')
  })

  it('renders checkboxes properly', () => {
    const onChange = jest.fn()

    function validateCheckbox() {
      expect(rendered().children.length).toEqual(1)
      const checkbox = rendered().children[0]
      expect(checkbox.tagName).toEqual('INPUT')
      expect(checkbox.type).toEqual('checkbox')
      return checkbox
    }

    // eslint-disable-next-line react/jsx-boolean-value
    render(<Editable value={true} onChange={onChange} />)
    expect(component.getEditorType()).toEqual('boolean')
    validateCheckbox()

    render(<Editable value="test" type="boolean" onChange={onChange} />)
    expect(component.getEditorType()).toEqual('boolean')
    const checkbox = validateCheckbox()

    Simulate.change(checkbox, { target: { value: false } })
    expect(onChange).toBeCalledWith(false, 'test')
  })
})
<commit_msg>Fix broken test<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import { Simulate } from 'react-dom/test-utils'
import Editable from './Editable'

describe('Editable', () => {
  let parent = null
  let component = null
  let rendered = null

  function render(element) { ReactDOM.render(element, parent) }

  beforeEach(() => {
    parent = document.createElement('div')
    component = ReactDOM.render(<Editable />, parent)
    // eslint-disable-next-line react/no-find-dom-node
    rendered = () => ReactDOM.findDOMNode(component)
  })

  it('renders classes properly', () => {
    render(<Editable className="test-class" />)
    expect(rendered().classList.contains('editable')).toEqual(true)
    expect(rendered().classList.contains('test-class')).toEqual(true)

    render(<Editable readonly />)
    expect(rendered().classList.contains('readonly')).toEqual(true)
  })

  it('raises change events properly', () => {
    const onChange = jest.fn()

    render(<Editable value="first" onChange={onChange} />)
    component.handleToggleEditing()

    const editor = rendered().children[0]
    expect(editor.value).toEqual('first')
    Simulate.change(editor, { target: { value: 'second' } })
    Simulate.blur(editor)
    expect(onChange).toBeCalledWith('second', 'first')
  })

  it('renders checkboxes properly', () => {
    const onChange = jest.fn()

    function validateCheckbox() {
      expect(rendered().children.length).toEqual(1)
      const checkbox = rendered().children[0]
      expect(checkbox.tagName).toEqual('INPUT')
      expect(checkbox.type).toEqual('checkbox')
      return checkbox
    }

    // eslint-disable-next-line react/jsx-boolean-value
    render(<Editable value={true} onChange={onChange} />)
    expect(component.getEditorType()).toEqual('boolean')
    validateCheckbox()

    render(<Editable value="test" type="boolean" onChange={onChange} />)
    expect(component.getEditorType()).toEqual('boolean')
    const checkbox = validateCheckbox()

    Simulate.change(checkbox, { target: { value: false } })
    expect(onChange).toBeCalledWith(false, 'test')
  })
})
<|endoftext|>


<commit_before>angular.module( 'gj.Form' ).directive( 'gjFormServerValidation', function()
{
	// Don't create a new scope.
	// This allows it to work with other directives.
	return {
		restrict: 'A',
		require: 'ngModel',
		link: function( scope, elem, attr, ngModel )
		{
			/**
			 * Any time the server response updates, check to see if this form control is invalid.
			 * If it is, we set it as invalid.
			 */
			scope.$watchCollection( attr.gjFormServerValidation, function( serverResponse )
			{
				if ( angular.isDefined( serverResponse ) && serverResponse ) {
					if ( angular.isDefined( attr.name ) && angular.isDefined( serverResponse[attr.name] ) ) {

						// Set the 'server' key as invalid.
						// This is a generic key saying that the server rejected the value.
						ngModel.$setValidity( 'server', false );

						// We set the view value to itself to set it as dirty.
						// This will force show the server error message since it thinks that it's invalid
						// and the value has changed.
						ngModel.$setViewValue( ngModel.$viewValue );
					}
				}
			} );

			/**
			 * Any time the value of the input changes, simply set the validity back to true.
			 * This clears out the server error whenever they change it.
			 */
			ngModel.$viewChangeListeners.push( function()
			{
				if ( angular.isDefined( ngModel.$error.server ) && ngModel.$error.server ) {
					ngModel.$setValidity( 'server', true );

					// Clear out the actual error from the serverErrors object now that we've dealt with it.
					if ( angular.isDefined( scope[attr.gjFormServerValidation] ) ) {
						if ( angular.isDefined( attr.name ) && angular.isDefined( scope[attr.gjFormServerValidation][attr.name] ) ) {
							delete scope[attr.gjFormServerValidation][attr.name];
						}
					}
				}
			} );
		}
	};
} );<commit_msg>Update how we set the dirty state in form-server-validation component.<commit_after>angular.module( 'gj.Form' ).directive( 'gjFormServerValidation', function()
{
	// Don't create a new scope.
	// This allows it to work with other directives.
	return {
		restrict: 'A',
		require: 'ngModel',
		link: function( scope, elem, attr, ngModel )
		{
			/**
			 * Any time the server response updates, check to see if this form control is invalid.
			 * If it is, we set it as invalid.
			 */
			scope.$watchCollection( attr.gjFormServerValidation, function( serverResponse )
			{
				if ( serverResponse ) {
					if ( angular.isDefined( attr.name ) && angular.isDefined( serverResponse[attr.name] ) ) {

						// Set the 'server' key as invalid.
						// This is a generic key saying that the server rejected the value.
						ngModel.$setValidity( 'server', false );

						// We set the model as dirty.
						// This will force show the server error message since it thinks that it's invalid
						// and the value has changed.
						ngModel.$setDirty();
					}
				}
			} );

			/**
			 * Any time the value of the input changes, simply set the validity back to true.
			 * This clears out the server error whenever they change it.
			 */
			ngModel.$viewChangeListeners.push( function()
			{
				if ( angular.isDefined( ngModel.$error.server ) && ngModel.$error.server ) {
					ngModel.$setValidity( 'server', true );

					// Clear out the actual error from the serverErrors object now that we've dealt with it.
					if ( angular.isDefined( scope[attr.gjFormServerValidation] ) ) {
						if ( angular.isDefined( attr.name ) && angular.isDefined( scope[attr.gjFormServerValidation][attr.name] ) ) {
							delete scope[attr.gjFormServerValidation][attr.name];
						}
					}
				}
			} );
		}
	};
} );
<|endoftext|>


<commit_before>var loopback = require('loopback');
var async = require('async');

module.exports = function(Todo/*, Base*/) {

  Todo.definition.properties.created.default = Date.now;

  Todo.beforeSave = function(next, model) {
    if (!model.id) model.id = 't-' + Math.floor(Math.random() * 10000).toString();
    next();
  };

  Todo.stats = function(filter, cb) {
    var stats = {};
    cb = arguments[arguments.length - 1];
    var Todo = this;

    async.parallel([
      countComplete,
      count
    ], function(err) {
      if (err) return cb(err);
      stats.remaining = stats.total - stats.completed;
      cb(null, stats);
    });

    function countComplete(cb) {
      Todo.count({completed: true}, function(err, count) {
        stats.completed = count;
        cb(err);
      });
    }

    function count(cb) {
      Todo.count(function(err, count) {
        stats.total = count;
        cb(err);
      });
    }
  };

  loopback.remoteMethod(Todo.stats, {
    accepts: {arg: 'filter', type: 'object'},
    returns: {arg: 'stats', type: 'object'}
  });
};
<commit_msg>Use Model.remoteMethod instead of loopback's fn.<commit_after>var loopback = require('loopback');
var async = require('async');

module.exports = function(Todo/*, Base*/) {

  Todo.definition.properties.created.default = Date.now;

  Todo.beforeSave = function(next, model) {
    if (!model.id) model.id = 't-' + Math.floor(Math.random() * 10000).toString();
    next();
  };

  Todo.stats = function(filter, cb) {
    var stats = {};
    cb = arguments[arguments.length - 1];
    var Todo = this;

    async.parallel([
      countComplete,
      count
    ], function(err) {
      if (err) return cb(err);
      stats.remaining = stats.total - stats.completed;
      cb(null, stats);
    });

    function countComplete(cb) {
      Todo.count({completed: true}, function(err, count) {
        stats.completed = count;
        cb(err);
      });
    }

    function count(cb) {
      Todo.count(function(err, count) {
        stats.total = count;
        cb(err);
      });
    }
  };

  Todo.remoteMethod('stats', {
    accepts: {arg: 'filter', type: 'object'},
    returns: {arg: 'stats', type: 'object'},
    http: { path: '/stats' }
  }, Todo.stats);
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bars: [],
      zip: '',
      message: null,
      fetching: true
    };
    this.getBars = this.getBars.bind(this)
    this.getAttendance = this.getAttendance.bind(this)
    this.listBars = this.listBars.bind(this)
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(event) {
    this.setState({ zip: event.target.value })
  }

  getBars(event) {
    this.setState({ bars: [] })
    event.preventDefault()

    fetch(`/yelp/${this.state.zip}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(`status ${response.status}`)
        }
        return response.json()
      })
      .then(json => {
        this.setState({
          bars: json,
          zip: '',
          fetching: false
        })
      })
      .then(() => this.getAttendance())
      .catch(e => {
        this.setState({
          message: `API call failed: ${e}`,
          fetching: false
        });
      })
  }

  getAttendance() {
    let barsArray = this.state.bars
    fetch('/yelp/activebars')
      .then(response => {
        if (!response.ok) {
          throw new Error(`status ${response.stats}`)
        }
        return response.json()
      })
      .then(json => {
        json.forEach((active_bar, idx) => {
          barsArray.forEach((bar, idx) => {
            if (bar.id === active_bar.bar_id) {
              barsArray[idx].numAttendees = active_bar.numAttendees
            }
          })
        })
      })
  }

  listBars() {
    let allBars = this.state.bars
    console.log(allBars[1].numAttendees)
    let listBars = allBars.map((bar, idx) => {
      if (bar.numAttendees) {console.log(bar.bar_id)}
      return
{bar.name}

    })
    return
{listBars}

  }

  render() {
    return (

Welcome to React

          {'This is '}

            {'create-react-app with a custom Node/Express server'}

          {this.state.fetching
            ? 'Fetching message from API'
            : this.state.message}

        <form onSubmit={this.getBars}>

            Location:
              <input type='text' value={this.state.zip} onChange={this.handleChange} />

          <input type='submit' value='Submit' />
        </form>

        {(this.state.bars.length > 0)
          ?
            this.listBars()
          :

False

}

    );
  }
}

export default App;<commit_msg>remove original App component<commit_after><|endoftext|>


<commit_before>var Wrapper = function() {
};

Wrapper._areParamTypesValidForWrapFunction = function(text, columnNum) {
        return (typeof(text) == "string") && (typeof(columnNum) == "number") && (columnNum > 0);
};

Wrapper._calculateLastBlankPos = function(text, columnNum) {
    var finished = false;
    var lastBlankPos = null;
    for (var i=0; i<columnNum+1; i++) {
        if (text.length > i) {
            if (text[i] == ' ') {
                lastBlankPos = i;
            }
        }
        else {
            finished = true;
        }
    }
    return {finished: finished, lastBlankPos: lastBlankPos};
};

Wrapper._processingText = function(state, strings, columnNum) {
    if ((!state.finished) && (state.lastBlankPos != null)) {
        strings.finalText = strings.finalText.concat(strings.tmpText.substr(0, state.lastBlankPos) + '\n');
        strings.tmpText = strings.tmpText.substr(state.lastBlankPos + 1, strings.tmpText.length);
    }
    else if (state.finished) {
        strings.finalText = strings.finalText.concat(strings.tmpText.substr(0, strings.tmpText.length));
    }
    else {
        strings.finalText = strings.finalText.concat(strings.tmpText.substr(0, columnNum) + '\n');
        strings.tmpText = strings.tmpText.substr(columnNum, strings.tmpText.length);
    }
    return strings;
};

Wrapper.wrap = function(text, columnNum) {
    if (this._areParamTypesValidForWrapFunction(text, columnNum)) {
        var strings = {tmpText: text, finalText: ""};
        var state = {finished: false, lastBlankPos: null};
        while (!state.finished) {
            state = this._calculateLastBlankPos(strings.tmpText, columnNum);
            strings = this._processingText(state, strings, columnNum);
        }
        return strings.finalText;
    }
    else {
        return "error";
    }
};

module.exports = Wrapper;<commit_msg>Minor changes to make this implementation of the word-wrap Kata follow more OOP principles (attributes and methods);  while the "wrap" function remains static (according to ES5 implementation of "static")<commit_after>var Wrapper = function(text, columnNum) {
    this.text = text;
    this.columnNum = columnNum;
};

Wrapper.prototype._areParamTypesValidForWrapFunction = function() {
    return (typeof(this.text) == "string") && (typeof(this.columnNum) == "number") && (this.columnNum > 0);
};

Wrapper.prototype._calculateLastBlankPos = function(currentText) {
    var finished = false;
    var lastBlankPos = null;
    for (var i=0; i<this.columnNum+1; i++) {
        if (currentText.length > i) {
            if (currentText[i] == ' ') {
                lastBlankPos = i;
            }
        }
        else {
            finished = true;
        }
    }
    return {finished: finished, lastBlankPos: lastBlankPos};
};

Wrapper.prototype._processingText = function(state, strings) {
    if ((!state.finished) && (state.lastBlankPos != null)) {
        strings.finalText = strings.finalText.concat(strings.tmpText.substr(0, state.lastBlankPos) + '\n');
        strings.tmpText = strings.tmpText.substr(state.lastBlankPos + 1, strings.tmpText.length);
    }
    else if (state.finished) {
        strings.finalText = strings.finalText.concat(strings.tmpText.substr(0, strings.tmpText.length));
    }
    else {
        strings.finalText = strings.finalText.concat(strings.tmpText.substr(0, this.columnNum) + '\n');
        strings.tmpText = strings.tmpText.substr(this.columnNum, strings.tmpText.length);
    }
    return strings;
};

Wrapper.wrap = function(text, columnNum) {
    var wrapper = new Wrapper(text, columnNum);
    if (wrapper._areParamTypesValidForWrapFunction()) {
        var strings = {tmpText: wrapper.text, finalText: ""};
        var state = {finished: false, lastBlankPos: null};
        while (!state.finished) {
            state = wrapper._calculateLastBlankPos(strings.tmpText);
            strings = wrapper._processingText(state, strings);
        }
        return strings.finalText;
    }
    else {
        return "error";
    }
};

module.exports = Wrapper;<|endoftext|>